A Practical Guide to Image Frequency- and Spatial-Domain Scribble Restoration in JavaScript

    This article explains how to implement interactive scribble-and-restore workflows in the browser using Canvas and JavaScript, covering inverse-matrix edits, magnitude and phase spectra, combined spectral edits, and row-derivative reconstruction, plus DFT/IDFT, mapping, and performance notes.

    As the web has evolved, browsers have become capable rich-client platforms. Among frontend use cases, Canvas- and WebGL-based image processing remains a focus. Scribbling on a transformed image and restoring it is both an engaging interaction and a practical way to teach digital image processing. This article looks at implementing inverse-matrix, magnitude-spectrum, phase-spectrum, and row-derivative scribble-and-restore modes in JavaScript in the page.

    Technical background: transform and restore

    A digital image can be represented in the spatial domain (pixel locations) or the frequency domain. The usual tool for moving from spatial to frequency domain is the 2D discrete Fourier transform (2D DFT).

    After the Fourier transform, the image splits into magnitude and phase:

    • Magnitude spectrum: energy of each frequency. Low frequencies relate to smooth regions and overall brightness; high frequencies to edges and fine texture.
    • Phase spectrum: spatial alignment of those frequencies. Phase carries much of the geometric structure of objects.

    “Scribble and restore” means applying a mathematical transform (for example a frequency-domain matrix or a spatial gradient matrix), drawing on the visualized transform, then inverting (for example inverse Fourier transform) back to the spatial image. That makes the visual effect of transform-domain parameters easy to see.

    Five core scribble-and-restore modes

    A complete interactive page needs these five transform-and-restore modes:

    1. Inverse-matrix scribble and restore

    In some advanced models an image is a large matrix and the transform includes inversion. Scribbling acts on matrix elements. Changing regions of the inverse matrix and restoring by matrix multiplication shows how forced local pixel changes propagate into overall color and brightness. It is a low-level perturbation experiment for global coupling in the image data structure.

    2. Magnitude-spectrum scribble and restore

    After the magnitude spectrum is visualized as a grayscale image, the user can draw on it (for example black in the low-frequency region to attenuate low-frequency energy, or white at selected frequencies to boost high-frequency energy). Restore keeps the original phase and uses the edited magnitude in the inverse Fourier transform. Brightness and contrast change clearly. Removing high frequencies blurs the image; boosting directional high frequencies can sharpen edges or add ringing along that direction.

    3. Phase-spectrum scribble and restore

    Phase is central to structure. Scribbling on the phase visualization and restoring typically changes the image more than magnitude edits. Because phase aligns frequency components in space, small phase changes can misalign edges, warp contours, or add geometric noise. This mode shows why phase matters for recognition and reconstruction.

    4. Simultaneous magnitude and phase scribble and restore

    A combined mode lets the user edit corresponding regions of both spectra. It offers the most freedom to degrade and reconstruct. In practice it can stress-test watermark robustness or how denoisers behave under complex frequency-domain contamination.

    5. Row-derivative scribble and restore

    Spatial local features matter as well. The row derivative (horizontal gradient) is the rate of change along the horizontal axis. Extract the row-derivative matrix, scribble (change horizontal gradient in places), then reconstruct by integration or another gradient-restore method. You can add or remove horizontal edges. This is relevant to seamless blending and Poisson editing.

    JavaScript implementation and key code

    On the web, use the HTML5 Canvas API for pixel-level data and JavaScript for the math.

    1. Pixel readout and preprocessing

    Load the image and obtain grayscale data:

    1. function getImageData(canvas, ctx, img) {
    2. ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    3. const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    4. const data = imageData.data;
    5. const grayData = new Float32Array(canvas.width * canvas.height);
    6. // Convert to grayscale
    7. for (let i = 0; i < data.length; i += 4) {
    8. const r = data[i], g = data[i+1], b = data[i+2];
    9. grayData[i / 4] = 0.299 * r + 0.587 * g + 0.114 * b;
    10. }
    11. return grayData;
    12. }

    2. Discrete Fourier transform (DFT)

    Native JavaScript has no FFT. For small images a basic 2D DFT is enough. When performance matters, run this in a Web Worker so the main thread and UI stay responsive.

    3. Interactive scribble capture and data merge

    Listen for mouse events on the Canvas and capture the stroke. Because the user draws on the visualized transform, map Canvas pixel coordinates back to indices in the frequency-domain complex matrix or the spatial matrix.

    1. canvas.addEventListener('mousemove', (e) => {
    2. if (!isDrawing) return;
    3. const rect = canvas.getBoundingClientRect();
    4. const x = Math.floor(e.clientX - rect.left);
    5. const y = Math.floor(e.clientY - rect.top);
    6. // Modify the matrix for the current mode
    7. // Example in magnitude-spectrum mode:
    8. modifyMagnitudeSpectrum(x, y, brushSize, brushValue);
    9. // Live preview of the scribble
    10. drawSpectrumCanvas();
    11. });

    4. Inverse transform and restore

    When the user finishes drawing and triggers restore, recombine the edited magnitude and phase into a complex matrix, run 2D IDFT, then normalize and draw back to the Canvas.

    Performance and practice

    • Size limits and scaling: Fourier transform cost is O(N^2 log N) or worse (naive O(N^4)). Cap input size (for example 256×256); downsample larger images first.
    • Web Worker concurrency: Put matrix transforms, DFT, and IDFT in a Worker and pass data with postMessage so drawing stays smooth.
    • Log visualization: Magnitude dynamic range is huge; a raw display is often black. Before showing the spectrum for scribbling, apply a log map: logSpectrum = log(1 + magnitude) so low-energy regions are visible.

    Closing

    Implementing frequency- and spatial-domain scribble-and-restore in the browser can produce compelling interactive apps and a bridge from abstract math to visible results. Understanding magnitude, phase, and derivatives helps with compression, feature extraction, filters, and other web image-processing work.