JavaScript Image Transformations: An Interactive Web Experiment for Doodling and Reconstruction
This article presents a browser-based image-processing experiment built with JavaScript, the Canvas API, and typed arrays. Users can load an image, transform it into different domains, doodle directly on the transformed data, and reconstruct the image through inverse operations. Five modes are covered: inverse matrix transforms, magnitude spectra, phase spectra, combined magnitude-and-phase editing, and row derivatives. The implementation also explains the mathematical principles, visualization techniques, interaction mapping, and performance considerations behind the experiment.
JavaScript Image Transformations: An Interactive Web Experiment for Doodling and Reconstruction
1. Project Background and Goals
A classic and intuitive image-processing experiment is to modify an image in a transform domain—such as the frequency domain, derivative domain, or another linear transform domain—and then apply the inverse transform to see how the image changes.
This type of experiment helps developers understand how information is distributed across a transform domain and why some transformations can be reversed.
With the browser Canvas API and typed arrays, it is possible to build the entire experiment with pure JavaScript and no backend:
- Load an image.
- Apply a forward transform.
- Doodle on the transformed representation.
- Apply the inverse transform.
- Display the reconstructed image.
The project includes five modes:
- Inverse matrix transforms
- Magnitude spectra
- Phase spectra
- Combined magnitude-and-phase editing
- Row derivatives
An AI-assisted coding tool can help generate the initial code structure, but the mathematical principles and engineering details still need to be understood and implemented carefully.
2. Overall Architecture
The web page can be organized as a single-page application with the following modules:
- Image loading: Use an
<input type="file">element to read a local image, draw it onto a hidden canvas, and extract pixel data withgetImageData. - Transform core: Implement forward and inverse transforms as pure functions. Inputs and outputs can be represented as two-dimensional floating-point arrays.
- Doodle interaction: Listen for
mousedown,mousemove, andmouseupevents on the canvas that visualizes the transformed data. The painted region is mapped back to transform-domain data, such as setting selected coefficients to zero. - Reconstruction display: Apply the inverse transform, normalize the result, and draw it to an output canvas.
For responsive performance, the image should generally be resized to 256×256 or 512×512 pixels. Converting the image to grayscale also avoids the threefold computational cost of processing separate RGB channels.
function toGray(imageData) {const { data, width, height } = imageData;const gray = new Float32Array(width * height);for (let i = 0; i < width * height; i++) {gray[i] = 0.299 * data[i*4] + 0.587 * data[i*4+1] + 0.114 * data[i*4+2];}return gray;}
3. Mode One: Doodling and Reconstruction with an Inverse Matrix Transform
A straightforward linear-transform experiment is to construct an invertible matrix. Let the vectorized image be x, and choose an orthogonal matrix A, such as a Hadamard matrix or a DCT basis matrix. The forward transform is:
y = A · x
The reconstruction is:
x̂ = Aᵀ · y
For an orthogonal matrix, the inverse is equal to its transpose.
In practice, it is not necessary to construct the complete matrix explicitly. A separable transform can be implemented by applying a one-dimensional transform across all rows and then across all columns.
When the user doodles on the transform representation, the selected coefficients in y can be set to zero. The reconstruction demonstrates different effects depending on which coefficients are removed:
- Removing coefficients associated with low-frequency bases damages the overall brightness and structure.
- Removing high-frequency coefficients mainly reduces fine details and makes the image appear blurred.
This experiment provides an intuitive demonstration of the energy-compaction properties of orthogonal transforms.
4. Modes Two and Three: Editing and Reconstructing Magnitude and Phase Spectra
4.1 Implementing FFT in the Browser
Frequency-domain experiments require a two-dimensional FFT. The core operation is an iterative radix-2 one-dimensional FFT combined with bit-reversal permutation.
function fft1d(re, im, invert) {const n = re.length;for (let i = 1, j = 0; i < n; i++) {let bit = n >> 1;for (; j & bit; bit >>= 1) j ^= bit;j ^= bit;if (i < j) {[re[i], re[j]] = [re[j], re[i]];[im[i], im[j]] = [im[j], im[i]];}}for (let len = 2; len <= n; len <<= 1) {const ang = 2 * Math.PI / len * (invert ? -1 : 1);const wr = Math.cos(ang), wi = Math.sin(ang);for (let i = 0; i < n; i += len) {let curR = 1, curI = 0;for (let k = 0; k < len / 2; k++) {const uR = re[i+k], uI = im[i+k];const vR = re[i+k+len/2] * curR - im[i+k+len/2] * curI;const vI = re[i+k+len/2] * curI + im[i+k+len/2] * curR;re[i+k] = uR + vR; im[i+k] = uI + vI;re[i+k+len/2] = uR - vR; im[i+k+len/2] = uI - vI;const nR = curR * wr - curI * wi;curI = curR * wi + curI * wr; curR = nR;}}}if (invert) for (let i = 0; i < n; i++) { re[i] /= n; im[i] /= n; }}
A two-dimensional FFT is obtained by applying the one-dimensional FFT to every row and then to every column.
Each complex coefficient can then be decomposed into magnitude and phase:
mag = Math.sqrt(re * re + im * im);phase = Math.atan2(im, re);
4.2 Editing Only the Magnitude Spectrum
The magnitude spectrum is usually displayed with logarithmic stretching. When the user paints on this visualization, the magnitude of the selected coefficients is set to zero while the original phase is preserved.
The modified complex coefficients are then reconstructed and passed to the inverse FFT.
Typical results include:
- Removing the central low-frequency region produces a high-pass-like image containing mostly edges and fine variations.
- Removing outer high-frequency regions produces a smoother and more blurred image.
This demonstrates that the magnitude spectrum largely represents the distribution of image energy and texture strength.
4.3 Editing Only the Phase Spectrum
In the opposite experiment, the magnitude remains unchanged while the phase is modified or erased.
The reconstructed image often loses its recognizable structure completely. In many cases, the original outline becomes difficult or impossible to identify.
This leads to a well-known observation in frequency-domain image processing:
The phase spectrum carries much of the structural and positional information, while the magnitude spectrum contributes more to the image’s visual intensity and texture characteristics.
4.4 Visualization Techniques
The dynamic range of a magnitude spectrum is usually very large. Direct linear display often results in an almost entirely black image.
A common solution is logarithmic compression:
displayValue = Math.log(1 + mag);
The spectrum can also be centered by shifting the zero-frequency component to the middle of the display. This makes the frequency distribution easier to inspect and provides a more convenient surface for doodling.
5. Mode Four: Editing Magnitude and Phase Together
This mode provides two separate visualization windows: one for magnitude and one for phase. The user can paint on either or both representations before reconstruction.
A useful comparison is to combine the magnitude from image A with the phase from image B. The resulting image usually has:
- The structural outline and spatial arrangement of image B
- The grayscale style and texture characteristics of image A
This further supports the distinction between the roles of magnitude and phase.
During reconstruction, the possibly modified magnitude and phase arrays are converted back into complex coefficients:
re[i] = mag[i] * Math.cos(phase[i]);im[i] = mag[i] * Math.sin(phase[i]);
The reconstructed complex array is then passed to the inverse FFT.
6. Mode Five: Row Derivatives and Reconstruction
The row-derivative mode demonstrates another reversible transformation.
For each row, calculate a forward difference:
d[i] = x[i + 1] - x[i]
To reconstruct the original row without loss, store the first pixel of each row. Reconstruction is then performed using a prefix-sum integration process.
// Forward transformfor (let x = 0; x < w - 1; x++) {diff[y*w+x] = gray[y*w+x+1] - gray[y*w+x];}// Inverse transformrow[0] = first[y];for (let x = 1; x < w; x++) {row[x] = row[x-1] + diff[y*w+x-1];}
If a segment of derivative values is set to zero, all subsequent pixels in that row receive a constant offset. The reconstructed image therefore contains a step-like artifact beginning at the edited position.
This effect illustrates how a local modification in the derivative domain can create a global cumulative change. Integration propagates the error toward the end of the row.
The experiment is useful for understanding differential encoding and gradient-domain image editing, including ideas related to Poisson-based reconstruction.
7. Engineering Considerations and Optimization
- Performance: A 512×512 two-dimensional FFT may take several tens of milliseconds on the browser’s main thread, which is generally acceptable for an interactive demonstration. Larger images should be processed in a Web Worker to avoid blocking the user interface.
- Numerical precision:
Float32Arrayis generally sufficient. After inverse transformation, clamp pixel values to the[0, 255]range. - Doodle coordinate mapping: Convert display coordinates to data coordinates carefully, especially when the visualization canvas is scaled. The brush radius should ideally be adjustable.
- Normalization: Keep spectrum visualization separate from the underlying data representation. Doodling should modify the actual transform-domain data rather than the cached display image.
8. Conclusion
This interactive web experiment demonstrates a complete “transform, doodle, and inverse-transform” workflow through five different modes.
- The inverse matrix transform illustrates energy concentration in an orthogonal basis.
- Separate magnitude and phase editing demonstrates that phase is strongly associated with image structure, while magnitude is more closely related to intensity and texture.
- The row-derivative experiment shows how local errors accumulate during integration and affect the remainder of a row.
The entire project can be implemented on the client side with roughly four to five hundred lines of code, making it suitable for image-processing courses, classroom demonstrations, and personal technical practice.
The same framework can later be extended to other reversible or partially reversible experiments, such as wavelet transforms and block-based DCT compression, to deepen understanding of transform-domain image processing.
