Frequency-Domain Doodling and Reconstruction in JavaScript: Principles and Implementation
This article explains how to treat an image as a signal, transform it with a 2D FFT, modify selected coefficients, and reconstruct it with the inverse transform using pure JavaScript in the browser. It covers the mathematical basis (2D DFT, magnitude and phase spectra, spectrum centering, row derivatives), the browser-side data path and iterative FFT implementation, five doodling modes (inverse matrix, magnitude, phase, both, and row derivative), and practical guidance on masks, numerical clipping, centering factors, and performance. The comparison shows that phase carries structural information while magnitude shapes overall appearance.
1. Background: Why Doodle After Transforming?
In image processing, treating the pixel matrix as a signal, mapping it to another representation space through a linear transform, modifying selected coefficients in that domain, and then applying the inverse transform back to the spatial domain is a widely used technical pattern. It supports frequency-domain filtering, texture analysis, information hiding, and robustness experiments.
The source material presents five variants: doodling on the inverse matrix result, on the magnitude spectrum, on the phase spectrum, on both magnitude and phase, and on the row derivative. All five answer the same question: which components of an image carry the key information that makes it look like the original. The discussion below follows the order: mathematical basis → engineering implementation → five modes → tuning and pitfalls → performance and productionization.
2. Mathematical Basis: From Pixel Matrix to Transform Domain
2.1 Two-Dimensional Discrete Fourier Transform
Let the image be $f(x,y)$ with size $M\times N$. Its 2D DFT is:
F(u,v) = Σ_x Σ_y f(x,y) · exp(-j2π(ux/M + vy/N))
The inverse transform is:
f(x,y) = (1/(MN)) Σ_u Σ_v F(u,v) · exp(+j2π(ux/M + vy/N))
In practice, the four nested loops implied by the definition ($O(M^2N^2)$) are avoided. Instead, a 1D FFT is applied to each row, then to each column, reducing the complexity to $O(MN\log(MN))$. Implementations therefore usually pad the dimensions to powers of two.
2.2 Magnitude Spectrum and Phase Spectrum
$F(u,v)$ is complex and can be written in polar form:
F(u,v) = A(u,v) · exp(jφ(u,v))A = sqrt(re² + im²) φ = atan2(im, re)
Numerous experiments show that the phase spectrum carries object contours, edges, and structural position information, while the magnitude spectrum mainly determines the overall brightness distribution and texture statistics. This is why doodling only the phase is the most destructive, whereas doodling only the magnitude still leaves the image barely recognizable.
2.3 Spectrum Centering
The DC component of the DFT output sits in the top-left corner, which is inconvenient for visual inspection and local doodling. In practice, multiplying by $(-1)^{x+y}$ moves the center to the middle of the image; multiplying by the same factor again before the inverse transform restores it.
2.4 Row Derivative
Applying a first-order difference to each row, $d(x,y)=f(x+1,y)-f(x,y)$, produces a horizontal gradient map. It suppresses slowly varying backgrounds and highlights vertical edges. Doodling on the derivative map and integrating it back reveals how reconstruction degrades once edge structure is damaged.
3. Browser-Side Implementation
3.1 Data Path
// Grayscale conversion + size aligned to a power of twofunction toGray(img, size) {const c = document.createElement('canvas');c.width = c.height = size;const ctx = c.getContext('2d');ctx.drawImage(img, 0, 0, size, size);const d = ctx.getImageData(0, 0, size, size).data;const g = new Float64Array(size * size);for (let i = 0; i < g.length; i++) {g[i] = 0.299 * d[i * 4] + 0.587 * d[i * 4 + 1] + 0.114 * d[i * 4 + 2];}return g;}
3.2 1D FFT (Iterative Version to Avoid Recursion Overhead)
function fft1(re, im, inverse) {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 = (inverse ? 2 : -2) * Math.PI / len;const wr = Math.cos(ang), wi = Math.sin(ang);for (let i = 0; i < n; i += len) {let cr = 1, ci = 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] * cr - im[i + k + len / 2] * ci;const vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;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 ncr = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = ncr;}}}if (inverse) for (let i = 0; i < n; i++) { re[i] /= n; im[i] /= n; }}
3.3 2D Forward and Inverse Transforms with Normalization
function fft2(re, im, inverse) {const n = Math.sqrt(re.length);for (let y = 0; y < n; y++) {const r = re.subarray(y * n, y * n + n), m = im.subarray(y * n, y * n + n);fft1(r, m, inverse);}for (let x = 0; x < n; x++) {const r = new Float64Array(n), m = new Float64Array(n);for (let y = 0; y < n; y++) { r[y] = re[y * n + x]; m[y] = im[y * n + x]; }fft1(r, m, inverse);for (let y = 0; y < n; y++) { re[y * n + x] = r[y]; im[y * n + x] = m[y]; }}}
Note that the 1D inverse transform already divides by $n$, so two passes complete the $1/(MN)$ normalization with no extra handling.
4. Design and Effects of the Five Doodling Modes
The unified flow is: forward transform → build mask → modify coefficients → inverse transform → take the real part and clip to 0–255.
Mode 1: Inverse Matrix Doodling
First invert the image matrix (this requires a square, full-rank matrix; real images are often singular, so a tiny perturbation or the pseudo-inverse is needed), then randomly perturb the elements of the inverse matrix, and finally multiply back by the original matrix. It demonstrates that invertibility in the linear-algebra sense does not equal visual recoverability: tiny perturbations are amplified by the condition number.
Mode 2: Magnitude Spectrum Doodling
// Modify magnitude only; phase stays unchangedconst A = Math.hypot(re[i], im[i]);const ph = Math.atan2(im[i], re[i]);const A2 = mask[i] ? A * (1 + noise) : A;re[i] = A2 * Math.cos(ph); im[i] = A2 * Math.sin(ph);
Effect: overall brightness and contrast change, while contours are largely preserved.
Mode 3: Phase Spectrum Doodling
Add random perturbations to the phase while leaving the magnitude untouched. The effect is the most severe: the structure collapses and the original image is often unrecognizable.
Mode 4: Doodling Both Magnitude and Phase
Apply perturbations of different strengths to both, covering a continuous range from slight distortion to complete unrecognizability in a controllable way. This suits graded robustness testing.
Mode 5: Row Derivative Doodling
Doodle on the derivative map, accumulate it back, and then combine it with the low-frequency component of the original image. It mainly damages edge sharpness and is suitable for studying the sensitivity of first-order differential operators to structural information.
5. Parameters, Pitfalls, and Tuning
- Mask shape: center low-pass, ring band-pass, and random scatter masks carry completely different destruction semantics; parameterize them to make comparisons easy.
- Numerical clipping: the inverse transform contains floating-point error, so always apply
Math.max(0, Math.min(255, v)). - Centering factor: the forward and inverse transforms must use $(-1)^{x+y}$ as a pair, otherwise the image shifts into a checkerboard pattern.
- Performance: running a 1024×1024 FFT on the main thread causes noticeable jank. Move it into a Web Worker, or optimize with blocking and a bit-reversal lookup table; if the runtime provides GPU compute capability, the butterfly operations can also be moved to shaders.
- Productionization: batch processing and result retention can be delegated to object storage, task scheduling to a message queue, and runtime metrics to logging and monitoring with alerting, forming an observable processing pipeline.
6. Summary
The comparison of the five modes yields a clear conclusion: phase is the skeleton of structural information, while magnitude is the cosmetic modifier of appearance statistics. Mastering four things—a correct 2D FFT implementation, paired centering, inverse-transform normalization, and mask design—is enough to reliably reproduce the whole “transform–doodle–reconstruct” experiment in a purely front-end environment and extend it into a general tool for image robustness evaluation, teaching demos, and algorithm validation.
