Interactive Image-Domain Doodling and Reconstruction with JavaScript
Build a browser-based teaching demo that lets users draw on pixel, Fourier magnitude, Fourier phase, combined magnitude-and-phase, and row-derivative representations, then reconstruct the image locally. The project demonstrates how different transforms distribute visual information and how errors propagate through inverse operations, using Canvas 2D, JavaScript numerical processing, and real-time doodling.
1. Project Background and Overall Approach
A classic experiment in image processing is to transform an image into the frequency domain or another representation domain, let users draw freely on the transformed data, and then apply the inverse transform to observe the result. This provides an intuitive demonstration of how information is distributed across different domains.
For example, damaging only the phase spectrum can make an image unrecognizable, while small changes to the magnitude spectrum may leave its overall structure largely intact.
This project implements the experiment as a browser-based teaching demo using only client-side technologies. It includes five modes:
- Doodling and reconstruction in the pixel domain using an inverse matrix
- Doodling and reconstruction of the image magnitude spectrum
- Doodling and reconstruction of the image phase spectrum
- Doodling and reconstruction of both magnitude and phase spectra
- Doodling and reconstruction in the image row-derivative domain
All calculations run locally in the browser, with no backend required.
2. Technology Choices and Page Structure
2.1 Core Technology Stack
- Canvas 2D: Displays images, reads pixels with
getImageData, and writes processed data withputImageData. - JavaScript array operations: Implements the discrete Fourier transform (DFT) or fast Fourier transform (FFT), derivatives, and matrix inversion.
- Doodling layer: Uses an additional transparent canvas to record user strokes. The strokes are applied to transformed-domain data through
globalCompositeOperationor pixel-level blending.
A typical layout contains three columns:
- The original image and transformed representation
- A central doodling canvas
- The reconstructed image, mode selector, and related controls
2.2 Processing Pipeline
The overall workflow can be represented as:
Original image → Forward transform F → Transform visualization→ User doodling → Corrupted transform data→ Inverse transform F⁻¹ → Reconstructed image
The main difference between modes is the definition of the transform function F. If transformation, visualization, doodling, and reconstruction are implemented as interchangeable modules, all five modes can share the same interaction logic.
3. Key Module Implementations
3.1 Pixel-Domain Inverse-Matrix Mode
Treat the grayscale image as a square matrix A. Generate a random invertible matrix M and encode the image as:
B = M · A
After the user draws on B, the modified image B' is reconstructed with:
A' = M⁻¹ · B'
Because matrix inversion can amplify errors, distortion may spread beyond the doodled area. This demonstrates how errors propagate through a linear transformation.
A simplified implementation is:
// Simplified example for an N×N grayscale matrixfunction encode(pixels, M) {return matMul(M, pixels); // B = M·A}function decode(B, Minv) {return matMul(Minv, B); // A' = M⁻¹·B'}
Gaussian-Jordan elimination can be used for matrix inversion. The implementation should handle numerical stability when diagonal elements are close to zero.
3.2 Magnitude and Phase Spectrum Modes
First apply a two-dimensional DFT or FFT to obtain a complex-valued matrix F(u, v). The magnitude and phase are calculated as follows:
magnitude = Math.sqrt(re * re + im * im);phase = Math.atan2(im, re);
For visualization, the magnitude spectrum should usually be log-scaled with log(1 + |F|) and centered so that low frequencies appear in the middle. Without these steps, useful features are difficult to see. The phase spectrum can be mapped directly from its angle range to grayscale values from 0 to 255.
Doodles can be applied in two ways:
- Direct replacement: Replace values in the doodled region with fixed frequency-domain values.
- Weighted blending: Interpolate according to the doodle opacity
α:
value' = (1 - α) · value + α · doodleValue
During reconstruction, rebuild the complex spectrum from the modified magnitude and phase:
re = mag * Math.cos(phase);im = mag * Math.sin(phase);
An inverse FFT can then be applied, using the real part of the result as the reconstructed image.
This mode reveals an important property of image representations:
- When only the magnitude spectrum is modified, the global structure is usually preserved, although contrast and fine details may be degraded.
- Even slight changes to the phase spectrum can make the image unrecognizable.
The phase carries important information about object locations and edges, making it highly influential in visual perception. The magnitude spectrum primarily describes energy distribution. This makes the experiment especially useful for explaining the role of phase information.
3.3 Simultaneous Magnitude-and-Phase Doodling
This mode allows the two spectra to be edited with separate canvases, or lets one stroke affect both. In implementation, two doodle masks are applied independently:
magDirty[i] = mix(mag[i], doodleMag[i], maskA[i]);phaseDirty[i] = mix(phase[i], doodlePhase[i], maskB[i]);
The reconstructed result usually resembles a combination of the effects produced by damaging each domain individually. However, the relationship is not strictly linear. Structural corruption caused by phase changes generally dominates the visual result.
3.4 Row-Derivative Mode
For each image row, calculate the horizontal difference:
d[x] = img[x + 1] - img[x]
The resulting values range from -255 to 255, so they must be offset and scaled to the range 0 to 255 for display.
Reconstruction uses cumulative integration from the first column:
img[x] = img[x - 1] + d[x - 1]
This introduces a classic error-accumulation problem. A local doodling error continues to propagate along the integration direction, producing horizontal stripes across the row.
This behavior contrasts with the frequency-domain modes:
- Damage in the derivative domain spreads regionally through integration.
- Damage in the frequency domain changes global image textures and structures.
To reduce distortion, apply zero-mean correction to each reconstructed row after integration to remove DC drift.
4. Performance and Interaction Optimizations
- Use FFT instead of direct DFT: For an
N × Nimage, a direct DFT hasO(N⁴)complexity, while a separable row-and-column FFT requires approximatelyO(N² log N). Image dimensions should preferably be powers of two, such as256 × 256; smaller images can be padded when necessary. - Process grayscale first: All five modes are easier and faster to implement on grayscale images. Processing all three RGB channels independently would add computational cost and make the visual behavior harder to interpret.
- Provide real-time previews: Listen for
pointermoveevents on the doodling canvas and trigger a throttled inverse transform. This lets users see reconstruction changes while drawing. - Preserve numerical precision: Use floating-point values throughout complex and matrix calculations. Clamp and round values only during visualization and when writing pixels back to the canvas.
5. Conclusion
This project is essentially a playable textbook on signal processing. With only a few hundred lines of front-end code, abstract concepts such as matrix invertibility, the different roles of Fourier magnitude and phase, and error propagation through differentiation and integration become visually observable experiments.
For front-end developers, the project also provides practical experience with pixel-level Canvas operations, complex-number calculations, and event throttling. It is a suitable introductory project for image processing and can later be extended with additional transform domains, such as two-dimensional convolution and wavelet transforms.
