Building an Interactive Image Frequency-Domain Painting and Restoration Tool in Pure JavaScript

    Learn how to build a browser-based tool that lets users paint directly in transform domains—matrix inverse, Fourier magnitude, phase, and row derivatives—and restore images back to the spatial domain using pure JavaScript. Covers the math, FFT optimization, and Canvas interaction details.

    Building an Interactive Image Frequency-Domain Painting and Restoration Tool in Pure JavaScript

    Background and Goals

    A classic, intuitive experiment in image processing education is to transform an image from the spatial domain into another mathematical domain (frequency domain, gradient domain, matrix domain, etc.), let students “paint” directly on that domain, then inverse-transform back to the spatial domain and observe the surprising changes. This kind of interactive experiment makes abstract concepts—magnitude spectra, phase spectra, matrix inverse transforms—much easier to grasp.

    The goal of this article is to build, entirely in the browser and using only JavaScript, an interactive web tool that supports painting and restoration across multiple transform domains. Five modes are covered:

    1. Painting and restoration on the image’s matrix inverse
    2. Painting and restoration on the image’s magnitude spectrum
    3. Painting and restoration on the image’s phase spectrum
    4. Painting on both magnitude and phase simultaneously
    5. Painting and restoration on the image’s row derivatives

    All computation happens on the client side with no server involvement, which means simple deployment, real-time interaction, and privacy by design.

    Overall Architecture

    Page Layout

    A “three-view linked” layout works well:

    • Left view: the original image or the visualization of the current transform domain (the painting canvas);
    • Right view: the restored spatial-domain image after inverse transformation;
    • Control panel: mode switching, parameter adjustment (e.g., the spectrum scaling factor gamma), brush size and color, reset and export buttons.

    Data Flow

    The processing pipeline looks like this:

    1. Load image → grayscale / resize to power of two → forward transform
    2. → visualize transform domain → user paints → inverse transform → display result

    The key point: painting happens on the visualized transform-domain image, but the painted pixels must be mapped back into complex-valued transform coefficients. The system therefore always keeps an internal copy of the transform result in complex form (two Float64 arrays for real and imaginary parts); the visualized image is only a “projection” used for user interaction.

    The Five Modes: Theory and Implementation

    1. Matrix Inverse Painting and Restoration

    Treat the grayscale image as an N×N matrix M, compute its inverse M⁻¹, and display it. Painting on the inverse view modifies certain elements of M⁻¹; inverting the modified matrix (M⁻¹)⁻¹ yields the “perturbed original image.”

    Implementation uses Gauss-Jordan elimination. Watch out for floating-point conditioning issues:

    1. function invertMatrix(A, n) {
    2. // Build the augmented matrix [A | I]
    3. const aug = new Float64Array(n * 2 * n);
    4. for (let i = 0; i < n; i++) {
    5. for (let j = 0; j < n; j++) {
    6. aug[i * 2 * n + j] = A[i * n + j];
    7. aug[i * 2 * n + n + j] = (i === j) ? 1 : 0;
    8. }
    9. }
    10. // Gaussian elimination with partial pivoting
    11. for (let col = 0; col < n; col++) {
    12. let pivot = col;
    13. for (let r = col + 1; r < n; r++) {
    14. if (Math.abs(aug[r * 2 * n + col]) >
    15. Math.abs(aug[pivot * 2 * n + col])) pivot = r;
    16. }
    17. // Swap rows, normalize, eliminate... (omitted)
    18. }
    19. return aug; // the right half is the inverse matrix
    20. }

    One caveat: matrices of ordinary photos are often nearly singular (adjacent pixels are highly correlated), so the inverse is numerically unstable. In practice, apply a small perturbation to the image (e.g., add a tiny positive value to the diagonal, similar to regularization) to guarantee invertibility—and explain this in the classroom.

    2. Magnitude Spectrum Painting and Restoration

    Apply a 2D discrete Fourier transform (DFT) to the image:

    1. F(u,v) = Σ Σ f(x,y) · e^(-j2π(ux/N + vy/N))

    The magnitude spectrum |F(u,v)| is typically displayed on a log scale (log(1+|F|)) with low frequencies centered (fftshift) for easier viewing. Painting directly modifies magnitude values while phase stays fixed; an inverse DFT then returns to the spatial domain.

    Expected behavior: modifying the magnitude spectrum mainly affects contrast and overall brightness structure, while geometric contours are largely preserved—structural information is mostly encoded in the phase.

    3. Phase Spectrum Painting and Restoration

    The phase spectrum is φ(u,v) = atan2(Im, Re). Painting modifies the phase while magnitude stays fixed; after the inverse transform, the “content positions” in the image become severely scrambled. This is the most direct demonstration of the classic conclusion that phase carries structural information.

    Implementation detail: the gray value g (0–255) of a painted pixel must first be normalized to the (-π, π] range before being written back as a phase, then the complex coefficients are rebuilt:

    1. // Rebuild complex coefficients from magnitude and phase
    2. F[i] = mag[i] * Math.cos(phase[i]);
    3. FIm[i] = mag[i] * Math.sin(phase[i]);

    4. Painting Magnitude and Phase Together

    In this mode, users can modify magnitude and phase on two separate canvases, or edit a combined view of both on a single canvas. The implementation is the same as the previous two sections, except that restoration uses both the modified magnitude and the modified phase. This mode is ideal for controlled comparisons: at equal painting intensity, phase perturbation causes far more visual damage than magnitude perturbation.

    5. Row Derivative Painting and Restoration

    Compute a horizontal difference for each row of the image, d(x,y) = f(x,y) - f(x-1,y), producing a row-derivative map. After the user paints on the derivative map, restoration integrates along the x direction via a per-row cumulative sum:

    1. for (let y = 0; y < h; y++) {
    2. let acc = leftCol[y]; // use the original leftmost column as the integration seed
    3. for (let x = 0; x < w; x++) {
    4. acc += d[y * w + x];
    5. restored[y * w + x] = acc;
    6. }
    7. }

    Because differentiation loses the absolute baseline of each row’s first column, restoration needs to borrow the original image’s leftmost column as the integration constant—otherwise the entire row drifts in brightness. This is itself a teachable moment about the null space of the differentiation operator.

    DFT Performance Optimization

    Running a full-size 2D DFT in the browser with a naive O(N⁴) double loop is completely impractical for a 512×512 image. Instead, use the separable approach: a 1D FFT row by row, then a 1D FFT column by column, reducing complexity to O(N² log N). In-place computation and bit-reversal permutation can reduce memory allocations. For further speedups, parallel computing or general-purpose GPU approaches such as WebGPU are options, but in pure JavaScript, a carefully optimized radix-2 FFT already achieves sub-second performance on 512×512 images—smooth enough for real-time interaction.

    Interaction and Engineering Details

    1. Canvas coordinate mapping: record the mouse trajectory while painting and convert screen coordinates to coefficient array indices. Since spectrum visualization is usually centered, the write-back must apply the inverse of fftshift.
    2. Data types: store transform coefficients in Float64Array for precision, converting to Uint8ClampedArray only for display.
    3. Undo and redo: push a snapshot of the complex coefficient arrays onto a stack before each stroke—trading memory for a better interaction experience.
    4. Exporting results: use the canvas’s toDataURL to export the restored image as a PNG.
    5. Edge cases: clamp all-zero rows, NaN overflows, and similar issues so a corrupted frame doesn’t ruin the experiment.

    Conclusion

    The web tool described in this article turns abstract mathematical transforms into hands-on, paintable experiments. The five modes correspond to core concepts: matrix inversion, Fourier magnitude and phase, joint frequency-domain editing, and the inverse of differentiation (integration). The whole solution is pure front-end with zero backend dependencies, making it suitable both as a teaching demo for image processing courses and as a comprehensive project for developers practicing numerical computing and Canvas interaction programming. Building on this framework, you can extend it with 2D directional derivatives, wavelet-domain painting, and other modes to create an even more complete image transform experimentation platform.