JavaScript Image Frequency-Domain and Spatial-Domain Doodle Restoration: A Practical Guide

    This article explores how to implement frequency-domain and spatial-domain image doodling and restoration in the browser using JavaScript. It covers the core principles of Fourier transforms, magnitude and phase spectra, and row derivatives, presents a practical code architecture, and walks through five doodle-and-restore modes along with performance optimization strategies such as Web Workers and downscaling.

    As web frontend technology continues to evolve, JavaScript-based image processing has moved far beyond simple CSS filters and Canvas pixel manipulation. Today, with advanced mathematical transformation theory, frontend developers can perform deep operations on an image’s frequency-domain and spatial-domain data directly in the browser. This article focuses on the theme of “doodling on transformed images and restoring them,” exploring in detail how to implement multiple image processing modes in JavaScript—including image inverse matrices, magnitude spectra, phase spectra, and row derivatives—while explaining the core algorithms and engineering practices behind them.

    1. Core Principles of Image Transformation and Doodle Restoration

    Before diving into code, we first need to understand how images are represented in different domains. Typically, an image can be expressed in the spatial domain (the pixel matrix we see with our eyes) and in the frequency domain (the frequency distribution obtained via the Fourier transform).

    1. Frequency-domain transformation (Fourier transform): Converting an image from the spatial domain to the frequency domain decomposes it into a magnitude spectrum and a phase spectrum. The magnitude spectrum reflects the energy of different frequency components and determines the brightness distribution of the image, while the phase spectrum contains the phase information of each frequency component and determines the image’s contours and structural features.
    2. Spatial-domain transformation: This mainly includes matrix-based linear transformations and differential operations such as the row derivative (gradient), which extracts edge information in a specific direction.
    3. Doodle and restoration mechanism: The core of doodle restoration lies in “intervention and reconstruction.” The developer first transforms the original image into a target domain, allows the user to draw on the visualized data of that domain (thereby modifying local data), and then maps the modified data back to a spatial-domain image via the inverse transform. This process not only intuitively demonstrates the physical meaning of data in various transform domains, but is also an effective way to validate the robustness of image processing algorithms.

    2. Core JavaScript Code Architecture and Implementation

    To implement this functionality in a web page, we need to build a complete loop that includes data transformation, interactive drawing, and inverse rendering. Below are the core modules of the system design along with illustrative code.

    1. Basic Data Structures and the Fourier Transform

    When performing a 2D Fourier transform (2D FFT) on the frontend, it is common practice— for performance reasons—to use TypedArrays (such as Float32Array) to store complex data, with real and imaginary parts stored either interleaved or separately.

    1. // Simplified core structure of a 2D FFT
    2. class ImageTransformer {
    3. constructor(width, height) {
    4. this.width = width;
    5. this.height = height;
    6. // Initialize real and imaginary arrays
    7. this.real = new Float32Array(width * height);
    8. this.imag = new Float32Array(width * height);
    9. }
    10. // Perform forward FFT, converting from spatial domain to frequency domain
    11. forwardFFT(sourceData) {
    12. // 1. Fill the real array with pixel data
    13. // 2. Perform 1D FFT along rows
    14. // 3. Perform 1D FFT along columns
    15. // 4. Return the complex matrix containing real and imag parts
    16. }
    17. // Perform inverse FFT, converting from frequency domain back to spatial domain
    18. inverseFFT() {
    19. // Reverse operation, returning visualizable pixel data
    20. }
    21. }

    2. Doodle Interaction and Data Mapping

    With the HTML5 Canvas API, we can capture the user’s mouse trajectory and map the drawn path onto the corresponding transform-domain data arrays.

    3. Five Doodle-and-Restore Modes in Depth

    Building on the architecture above, we can implement five different image transformation doodle-and-restore modes, each highlighting different image characteristics.

    1. Doodling and Restoring the Image Inverse Matrix

    In this mode, the image is treated as a large matrix undergoing a linear inverse transformation. When the user doodles in the inverse-matrix representation, they are effectively altering the weights of certain linear bases of the image. The restoration process reconstructs the image through matrix multiplication, and the doodled regions appear on the original image as geometrically patterned distortions or texture overlays. This mode is well suited for understanding the role of linear algebra in image compression and feature extraction.

    2. Doodling and Restoring the Magnitude Spectrum

    The magnitude spectrum is typically displayed on a logarithmic scale with the frequency domain centered (low frequencies in the center, high frequencies at the edges). When the user doodles in the central region of the magnitude spectrum, they effectively block or amplify the image’s low-frequency components, causing the restored image to become blurred or to shift abruptly in brightness. Doodling near the edges affects high-frequency components, making the restored image’s edges sharper or producing ringing artifacts. This mode vividly confirms the theory that “low frequencies define the overall appearance, while high frequencies define the details.”

    3. Doodling and Restoring the Phase Spectrum

    The phase spectrum is the most critical information for image recognition. Experiments show that if the magnitude spectrum is preserved while the phase spectrum is completely scrambled, the image becomes unrecognizable. In the phase-spectrum doodle mode, when the user draws lines on the phase map and the image is restored, the original image’s contours and structures undergo drastic displacement and reorganization, while the overall brightness distribution remains nearly unchanged. This mode profoundly reveals the dominant role of phase in defining image structure.

    4. Doodling and Restoring the Magnitude and Phase Spectra Simultaneously

    This mode displays the magnitude and phase spectra side by side or overlaid. The user can doodle on both simultaneously, and the restoration combines the modified magnitude and phase in an inverse FFT. This composite operation produces extremely complex visual effects—both dramatic brightness changes and structural tearing—making it a comprehensive test of frequency-domain image processing capabilities.

    5. Doodling and Restoring the Row Derivative

    The row derivative is a spatial-domain differential operation that reflects the rate of change of pixel values in the horizontal direction. In this mode, the system computes and displays the image’s horizontal gradient map. Doodling on the gradient map is equivalent to artificially injecting or erasing horizontal edge information. During restoration—by integrating the gradient map (or performing Poisson reconstruction)—the resulting image exhibits noticeable horizontal stripes or enhanced edges at the doodled locations. This is highly valuable for frontend visualization of image sharpening and edge detection algorithms.

    4. Performance Optimization and Engineering Best Practices

    Executing computationally intensive math in the browser (such as a 2D FFT on a large image) can easily block the main thread and cause page jank. Therefore, the following optimizations should be adopted in real-world engineering:

    1. Introduce Web Workers: Move time-consuming tasks such as Fourier transforms and matrix operations into Web Workers, communicating with the main thread via postMessage to keep UI interactions smooth.
    2. Use SharedArrayBuffer: When cross-origin isolation configuration permits, the main thread and Workers can share memory, avoiding the copy overhead of large Float32Array data.
    3. Downsampling: For very large images, apply Gaussian pyramid downsampling before transformation, keeping the processing size within 512x512 or 1024x1024, then upscale the result with interpolation to balance performance and quality.
    4. On-demand re-rendering: During doodling, there is no need to run a full-image inverse transform on every mouse move. Use partial updates or throttling, and trigger a complete restoration computation only when the mouse is released.

    5. Conclusion

    Implementing frequency-domain and spatial-domain image doodling and restoration with JavaScript is not only a highly engaging frontend engineering exercise, but also an excellent way to deeply understand the underlying logic of digital image processing. From the separation of magnitude and phase in the Fourier transform to gradient operations in the spatial domain, each mode converts abstract mathematical formulas into intuitive visual feedback. In production environments, combined with modern frontend asynchronous computing capabilities and memory management techniques, these techniques can be widely applied to online image editors, visual teaching tools, and intelligent visual analysis platforms, delivering richer and more professional image processing experiences to users.