Image Transform, Doodle, and Restoration Web Demo: A Hands-On Guide with AI Coding Tools
This article walks through building a pure front-end web application (HTML + Canvas + vanilla JavaScript) that demonstrates a classic image processing experiment: apply an invertible mathematical transform to an image, doodle on the transformed result, then apply the inverse transform to see how the doodle marks spread across the reconstructed image. Powered by AI coding tools, the demo covers five experiment modes: inverse matrix, magnitude spectrum, phase spectrum, combined magnitude and phase spectrum, and row derivative. It explains the underlying math, shares the full implementation architecture, and offers practical performance advice for educators and developers.
Building an Image Transform, Doodle, and Restoration Web Demo with AI Coding Tools
1. Background and Goals
Image processing includes a highly intuitive teaching experiment: first apply an invertible mathematical transform to an image, producing an intermediate result that looks completely different; then doodle freely on that intermediate result (locally modifying pixel values); finally apply the inverse transform and observe how the doodle marks get “spread” or “reshaped” across the original image. This “transform — doodle — restore” workflow vividly demonstrates how information is distributed in different transform domains, making it an excellent way to understand the role of Fourier analysis and linear algebra in image processing.
This article shows how to use AI coding tools to quickly build a pure front-end demo page (HTML + Canvas + vanilla JavaScript) with the following five experiment modes:
- Image inverse matrix doodle and restoration
- Image magnitude spectrum doodle and restoration
- Image phase spectrum doodle and restoration
- Simultaneous doodle and restoration on the magnitude and phase spectra
- Image row derivative doodle and restoration
2. Core Mathematical Principles
2.1 Invertible Linear Transforms and Inverse Matrix Doodling
Treat an N×N grayscale image as a matrix X. Choose an invertible matrix A and compute the transform Y = AX. Since A is invertible, restoration is X’ = A⁻¹Y’. When we doodle on Y to get Y’, each doodled pixel is “back-projected” by the inverse transform onto an entire row (or column) of the original image, producing full-length stripe artifacts. This intuitively shows that each output pixel in a matrix row transform encodes information from an entire input row.
// Example: an orthogonal matrix built from DCT-II basis functions;// for orthogonal matrices, the inverse is simply the transposefunction buildDCTMatrix(N) {const A = [];for (let k = 0; k < N; k++) {const row = [];const c = k === 0 ? Math.sqrt(1 / N) : Math.sqrt(2 / N);for (let n = 0; n < N; n++) {row.push(c * Math.cos(Math.PI * (n + 0.5) * k / N));}A.push(row);}return A;}
2.2 Fourier Transform and Magnitude/Phase Spectra
After applying the 2D discrete Fourier transform (2D DFT) to an image, each frequency-domain coefficient is a complex number that can be decomposed into:
- Magnitude spectrum: |F(u,v)|, reflecting the energy strength of each frequency component;
- Phase spectrum: ∠F(u,v), reflecting the spatial position information of each frequency component.
Extensive research has shown that the phase carries most of an image’s structural information — an image reconstructed with only the phase (with the magnitude set to a constant) still shows recognizable outlines, whereas reconstructing with only the magnitude yields almost nothing recognizable. The doodle experiment confirms this nicely: doodling on the magnitude spectrum leaves the overall image structure intact after restoration, producing only global ripple artifacts; doodling on the phase spectrum introduces directional stripes or even localized structural distortion at the corresponding frequencies.
// 1D DFT (educational version, O(N^2) — sufficient for small demo images)function dft1d(re, im, inverse) {const N = re.length;const outRe = new Array(N).fill(0);const outIm = new Array(N).fill(0);const sign = inverse ? 1 : -1;for (let k = 0; k < N; k++) {for (let n = 0; n < N; n++) {const ang = sign * 2 * Math.PI * k * n / N;outRe[k] += re[n] * Math.cos(ang) - im[n] * Math.sin(ang);outIm[k] += re[n] * Math.sin(ang) + im[n] * Math.cos(ang);}if (inverse) { outRe[k] /= N; outIm[k] /= N; }}return [outRe, outIm];}// 2D DFT: transform rows first, then columns (separability)function dft2d(data, N, inverse) {// data: {re: Float64Array, im: Float64Array}, length N*Nfor (let y = 0; y < N; y++) {const reRow = [], imRow = [];for (let x = 0; x < N; x++) {reRow.push(data.re[y * N + x]);imRow.push(data.im[y * N + x]);}const [r, i] = dft1d(reRow, imRow, inverse);for (let x = 0; x < N; x++) {data.re[y * N + x] = r[x];data.im[y * N + x] = i[x];}}for (let x = 0; x < N; x++) {const reCol = [], imCol = [];for (let y = 0; y < N; y++) {reCol.push(data.re[y * N + x]);imCol.push(data.im[y * N + x]);}const [r, i] = dft1d(reCol, imCol, inverse);for (let y = 0; y < N; y++) {data.re[y * N + x] = r[y];data.im[y * N + x] = i[y];}}}
Extracting and reconstructing magnitude and phase:
function toMagPhase(data, idx) {const mag = Math.hypot(data.re[idx], data.im[idx]);const pha = Math.atan2(data.im[idx], data.re[idx]);return [mag, pha];}function fromMagPhase(mag, pha) {return [mag * Math.cos(pha), mag * Math.sin(pha)];}
Note: for clearer spectrum visualization, you typically need to take the logarithm of the magnitude (log(1+|F|)) and shift the zero-frequency component to the center. However, the uncompressed raw magnitude values must be used for the inverse transform, and doodle modifications should be mapped back into linear magnitude space — otherwise the restored image will be distorted.
2.3 Row Derivative (Difference) Doodling and Restoration
The row-wise difference is defined as D(x,y) = I(x+1,y) − I(x,y). Differencing loses the absolute value of the first pixel in each row, so to make it “restorable,” you need to store a baseline value per row (for example, the first pixel of each row). Restoration is a running sum along each row:
I(x,y) = I(0,y) + Σ D(k,y), k = 0..x-1
When you doodle on the difference image, the doodle propagates to the right as a horizontal brightness step from the doodle point to the end of the row after restoration. This vividly demonstrates the error propagation property of difference encoding — a challenge that all difference-based and predictive coding schemes must address.
3. Web Implementation
3.1 Overall Architecture
The page uses a three-canvas layout:
- Canvas A (original image): loads and displays the user-uploaded image;
- Canvas B (transform domain): displays the transformed result and supports mouse doodling;
- Canvas C (restored image): after clicking a button, applies the inverse transform to B and displays the result.
A central state object manages everything:
const state = {size: 128, // resize to a small square image for performance and visual claritymode: 'inverseMatrix', // current experiment modeoriginal: null, // grayscale data of the original imagetransformed: null, // transform-domain data (used for restoration)brushSize: 8,};
3.2 Doodle Interaction
Listen for pointer events on Canvas B, write the doodle strokes directly into the corresponding transform-domain data, and refresh the display:
canvasB.addEventListener('pointermove', (e) => {if (!drawing) return;const { x, y } = getCanvasCoord(e);applyBrush(state.transformed, x, y, state.brushSize, state.mode);renderTransformed();});
Doodling means different things in different modes: in inverse matrix mode it directly modifies matrix element values; in magnitude spectrum mode it modifies magnitudes; in phase mode it modifies phase angles (you can map stroke grayscale to the [−π, π] range). Wrap these behaviors in a strategy pattern to keep the logic clean.
3.3 Performance and Practical Tips
- Control image size: the naive DFT has O(N⁴) complexity, so scale the demo image down to 64×64 or 128×128. For larger images, switch to a radix-2 FFT algorithm (the standard fast Fourier transform approach), reducing complexity to O(N²logN).
- Avoid blocking the main thread: per-pixel transform computations are heavy, so run them in a Web Worker, or at least show a loading state before computing, to keep interactions smooth.
- Numerical stability: in inverse matrix mode, prefer orthogonal transform matrices (such as DCT or Walsh matrices), whose inverse is simply the transpose — this avoids error accumulation from numerical matrix inversion.
- Separate data from display: always maintain one floating-point array of “true values” and one 8-bit grayscale mapping “for display.” Doodling and the inverse transform operate on the true values; the display layer only visualizes them.
4. Experimental Observations and Teaching Value
Comparing the five experiment modes yields several important conclusions:
- Inverse matrix mode: doodles produce regular global stripes in the restored image, showing the global coupling of linear transforms;
- Magnitude spectrum mode: doodles mainly cause global ripples and brightness shifts, while image structure remains largely intact;
- Phase spectrum mode: even a few doodle strokes cause obvious structural distortion, confirming the classic finding that “phase dominates structure”;
- Combined magnitude + phase doodling: both effects stack, making it easy to observe the separate contributions of energy and position information;
- Row derivative mode: doodles propagate one-way to the right, vividly illustrating the error diffusion problem in difference encoding.
These experiments are highly instructive for teaching image and signal processing courses, and for building intuition about compression coding, frequency-domain filtering, and related engineering practices.
5. Summary and Outlook
With the help of AI coding tools, this article built a pure front-end “transform — doodle — restore” demo web page with five experiment modes — inverse matrix, magnitude spectrum, phase spectrum, combined magnitude and phase, and row derivative — and systematically covered the underlying math, code structure, and performance optimizations. Possible future extensions include adding FFT support for larger images, adding frequency-domain filter design experiments (low-pass/high-pass/band-stop doodling), supporting per-channel processing of color images, and deploying the static demo to object storage or static site hosting services for easy sharing in educational settings.
