JavaScript Image Transform-Domain Doodling and Reconstruction: A Practical Guide
This article explores how to implement image doodling and reconstruction across five transform domains using native JavaScript and Canvas, with no third-party libraries. It covers a reusable 2D DFT/IDFT, inverse-matrix blocks, magnitude spectrum, phase spectrum, combined magnitude-and-phase perturbation, and row-derivative representation. For each mode, it explains the principle, implementation approach, and expected reconstruction behavior, followed by practical notes on performance, numerical stability, and interactive UI design. Readers will gain a low-cost, browser-based testbed for teaching demos, algorithm prototyping, and image robustness experiments.
1. Background and Overall Approach
In digital image processing, “doodling” usually means injecting local perturbations into an image on purpose. The traditional approach modifies pixels directly in the spatial domain, where the perturbation is strongly coupled with the content and it is hard to observe how different frequency components contribute to the final image. This article takes a different angle: first transform the image into another mathematical representation domain, apply the perturbation in that domain, then transform back to the spatial domain to observe the reconstruction result. Because the transform is linear and reversible (within numerical precision limits), as long as the perturbation is controlled, you can quantitatively study “what was changed and how the image changes.”
The five modes listed in the source material happen to cover five representative classes of representation domains:
- Inverse-matrix domain: split the image into blocks treated as matrices, invert or approximately invert them, then doodle in the inverse domain;
- Magnitude spectrum domain: the modulus after a 2D Fourier transform;
- Phase spectrum domain: the argument after a 2D Fourier transform;
- Doodling magnitude and phase at the same time;
- Row-derivative domain: a first-order difference representation along the row direction.
The following sections give the principle, implementation highlights, and sample code for each mode. All code uses native JavaScript + Canvas and depends on no third-party library.
2. Core Utility: 2D Discrete Fourier Transform
Browsers have no ready-made FFT implementation, so the most reliable approach is to write a reusable 2D DFT/IDFT yourself. To control complexity, images are usually grayscaled and scaled down to 64×64 or 128×128 before the transform.
function gray(ctx, w, h) {const d = ctx.getImageData(0, 0, w, h).data;const g = new Float64Array(w * h);for (let i = 0; i < w * h; i++) {g[i] = 0.299 * d[i*4] + 0.587 * d[i*4+1] + 0.114 * d[i*4+2];}return g;}function dft2(re, im, w, h, inverse) {const outRe = new Float64Array(w*h), outIm = new Float64Array(w*h);const sign = inverse ? 1 : -1;for (let v = 0; v < h; v++) {for (let u = 0; u < w; u++) {let sr = 0, si = 0;for (let y = 0; y < h; y++) {for (let x = 0; x < w; x++) {const a = sign * 2 * Math.PI * (u*x/w + v*y/h);const c = Math.cos(a), s = Math.sin(a);const idx = y*w + x;sr += re[idx]*c - im[idx]*s;si += re[idx]*s + im[idx]*c;}}const o = v*w + u;outRe[o] = inverse ? sr/(w*h) : sr;outIm[o] = inverse ? si/(w*h) : si;}}return [outRe, outIm];}
In production, dft2 should be replaced with a divide-and-conquer FFT to reduce complexity from O(N⁴) to O(N²logN), but direct DFT is easier to read for teaching and prototyping.
3. Mode 1: Inverse-Matrix Domain Doodling and Reconstruction
Split the image into 8×8 blocks and treat each block as a matrix A. Invert A to get A⁻¹, randomly modify several elements of A⁻¹, then multiply back by the inverse of A (that is, (A⁻¹)⁻¹) to reconstruct the block. Since (A⁻¹)⁻¹ = A, there is perfect reconstruction without doodling; with doodling, the error is amplified, giving an intuitive view of matrix inversion’s sensitivity to noise.
function inv3(m){ /* 3x3 inverse via the adjugate method, omitted */ }function blockInvDoodle(img, w, h, bs, doodle){const out = new Float64Array(w*h);for(let by=0; by<h; by+=bs){for(let bx=0; bx<w; bx+=bs){const A=[], B=[];for(let y=0;y<bs;y++){ A[y]=[]; B[y]=[];for(let x=0;x<bs;x++){ A[y][x]=img[(by+y)*w+bx+x]; B[y][x]=A[y][x]; } }const Ai = inv3(A); doodle(Ai);const Rec = inv3(Ai);for(let y=0;y<bs;y++)for(let x=0;x<bs;x++) out[(by+y)*w+bx+x]=Rec[y][x];}}return out;}
Key points: blocks that are too small are numerically unstable, while blocks that are too large increase computation. Use 4×4 or 8×8, and clamp results to [0,255].
4. Mode 2: Magnitude Spectrum Doodling and Reconstruction
The magnitude spectrum |F(u,v)| determines the image’s overall energy distribution and contrast structure. Painting the low-frequency central region black or randomly smearing it, then combining with the original phase spectrum for the inverse transform, reveals the phenomenon where the image “skeleton” is destroyed but the texture remains.
const [re, im] = dft2(img, new Float64Array(w*h), w, h, false);const mag = new Float64Array(w*h), pha = new Float64Array(w*h);for(let i=0;i<w*h;i++){ mag[i]=Math.hypot(re[i],im[i]); pha[i]=Math.atan2(im[i],re[i]); }doodle(mag); // doodle on the magnitude spectrumconst nr = new Float64Array(w*h), ni = new Float64Array(w*h);for(let i=0;i<w*h;i++){ nr[i]=mag[i]*Math.cos(pha[i]); ni[i]=mag[i]*Math.sin(pha[i]); }const rec = dft2(nr, ni, w, h, true)[0];
5. Mode 3: Phase Spectrum Doodling and Reconstruction
The phase spectrum carries information about object position and edges. Doodling only the phase while keeping the magnitude produces a reconstruction with a “misaligned content, drifting edges” appearance, a classic demonstration of the importance of phase.
doodle(pha); // modify only the phasefor(let i=0;i<w*h;i++){ nr[i]=mag[i]*Math.cos(pha[i]); ni[i]=mag[i]*Math.sin(pha[i]); }const rec = dft2(nr, ni, w, h, true)[0];
6. Mode 4: Doodling Magnitude and Phase Simultaneously
Perturbing both at once usually degrades the reconstruction into noise-like texture, illustrating that neither component can be missing. Implementation simply calls the doodle function on both mag and pha in the same loop, then combines them for the inverse transform; the code is fully reused from the previous two sections.
7. Mode 5: Row-Derivative Domain Doodling and Reconstruction
The row derivative d(x,y)=I(x,y)−I(x,y−1) is a high-pass representation. Doodling it is equivalent to injecting horizontal stripe artifacts; reconstruction is done by accumulation: I(x,y)=I(x,0)+Σd. Because accumulation accumulates error, the doodle amplitude must be very small, otherwise brightness drift appears.
const d = new Float64Array(w*h);for(let y=1;y<h;y++)for(let x=0;x<w;x++) d[y*w+x]=img[y*w+x]-img[(y-1)*w+x];doodle(d);const rec = new Float64Array(w*h);for(let x=0;x<w;x++){ rec[x]=img[x];for(let y=1;y<h;y++) rec[y*w+x]=rec[(y-1)*w+x]+d[y*w+x]; }
8. Engineering Practices and Performance Tips
- Size control: use 64×64 in the prototype stage for smooth interaction; in production, run the FFT in a Web Worker to avoid blocking the main thread.
- Numerical stability: both inverse-matrix and accumulation-based reconstruction need boundary clamping and small-value regularization to prevent Inf/NaN from spreading.
- Interaction design: use a three-column layout with the original image on the left, the reconstruction on the right, and a doodle canvas at the bottom; make the brush size adjustable, and throttle recomputation for real-time triggering.
- Visualization: use color-scale mapping to display the magnitude and phase spectra, making them easier to explain in teaching.
- For cloud batch processing, you can put images in object storage and have a stateless compute service on a container platform schedule them uniformly, with logs and monitoring going through standard logging and monitoring/alerting categories, avoiding handling large transforms all at once on the client side.
9. Summary
Together, the five modes show that image representations in different transform domains carry different semantics: the magnitude spectrum leans toward energy and contrast, the phase spectrum toward structure and position, the row derivative toward horizontal detail, and the inverse-matrix domain amplifies numerical sensitivity. Understanding these representations and their reversible-transform pairings lets you build an interactive image transform-domain doodling and reconstruction testbed in the browser using pure JavaScript, providing a low-cost validation environment for teaching demos, algorithm prototyping, and image robustness research.
