Pure Front-End Image Transform Doodling and Restoration: A Web-Based Practice

    This article presents a pure browser-based implementation of the classic "transform–doodle–restore" image processing experiment, built entirely with HTML, Canvas, and JavaScript. It covers five transform modes (inverse matrix transform, magnitude spectrum, phase spectrum, combined magnitude and phase, and row-wise derivative), explains their underlying principles, and details key implementation techniques including 2D FFT, pixel data management, doodle interaction design, and performance optimization—no backend required.

    Pure Front-End Image Transform Doodling and Restoration: A Web-Based Practice

    1. Background and Overall Approach

    A classic experiment in image processing education goes like this: map an image into another domain through an invertible mathematical transform, deliberately “doodle” in the transform domain (i.e., modify part of the data), then apply the inverse transform to restore the image and observe how the doodling affects the final result. This kind of experiment vividly reveals the energy distribution in the frequency domain, the relationship between phase and structural information, and how local linear operations affect the entire image.

    Traditionally, such experiments rely on desktop numerical computing environments. This article introduces a pure browser-based solution: using only HTML, Canvas, and JavaScript, you can complete the entire loop from image loading, transform computation, and doodle interaction to inverse-transform restoration, with no backend service at all. This approach is easy to deploy and share, making it ideal for teaching demos and technical presentations.

    The overall page architecture can be divided into four layers:

    1. Image input layer: load an image via file picker or drag-and-drop, draw it onto a Canvas, and read the pixel data;
    2. Transform computation layer: perform the forward transform according to the current mode (e.g., 2D DFT, row-wise difference, matrix transform);
    3. Interactive doodle layer: listen for mouse or touch events, paint over the visualization of the transform domain, and record the modified data regions;
    4. Inverse-transform restoration layer: execute the inverse transform to reconstruct the image from the doodled data and display the comparison.

    2. Technical Principles of the Five Transform Modes

    2.1 Doodling and Restoration via Inverse Matrix Transform

    This mode treats the image’s pixel matrix (processed per channel) as a numeric matrix and left-multiplies it by an invertible matrix T to obtain the transform result Y = T·X. Doodling directly modifies elements of Y, and restoration reconstructs X’ = T⁻¹·Y’ by left-multiplying Y’ with the inverse of T. Because matrix multiplication mixes values globally, painting a small region in the transform domain typically produces visible effects across entire rows or columns after restoration. This “pull one hair and the whole body moves” effect nicely demonstrates the global nature of linear transforms.

    Implementation notes:

    • Choose an invertible transform matrix with a small condition number (such as a perturbed orthogonal matrix) to avoid numerical instability during inversion;
    • Matrix inversion can be implemented with Gaussian elimination; for larger images, limit the block size involved in the computation to a few hundred rows/columns to keep interaction smooth.

    2.2 Doodling and Restoration on the Magnitude Spectrum

    This mode is based on the two-dimensional discrete Fourier transform (DFT). Applying the DFT to a grayscale image yields a complex spectrum F(u,v), which is decomposed into magnitude |F| and phase φ. If you modify only the magnitude while keeping the phase unchanged, then apply the inverse DFT, the restored image largely retains its overall structure (edges and contours), while brightness and contrast change noticeably. This experiment intuitively validates the classic conclusion that “phase carries the structural information.”

    The magnitude spectrum has an extremely large dynamic range, so logarithmic compression is required for visualization—for example, display = log(1 + |F|)—and the spectrum should be shifted so its center lies at the image center for easier observation.

    2.3 Doodling and Restoration on the Phase Spectrum

    Opposite to the magnitude mode, this mode keeps the magnitude unchanged and modifies only the phase. Practice shows that even destroying a small local portion of the phase causes severe structural distortion in the restored image, sometimes rendering it unrecognizable. Placing the magnitude mode and phase mode side by side is one of the most convincing demonstrations for learning frequency-domain image processing.

    2.4 Doodling on Magnitude and Phase Simultaneously

    This mode combines the previous two: doodling acts on both the magnitude and phase components. The restoration result exhibits both brightness distortion and structural damage, and can be used to simulate complex frequency-domain damage scenarios, such as the combined effects of compression artifacts and transmission errors on an image.

    2.5 Doodling and Restoration on Row-Wise Derivatives

    This mode applies a forward difference to each row of the image: D[i][j] = X[i][j+1] - X[i][j]. The difference result highlights horizontal edge information. Restoration is a row-by-row cumulative integration, but differencing loses the baseline value of the first pixel in each row, so the original value of each row’s first pixel must be stored separately as the integration constant; otherwise, the restored image will exhibit row-by-row brightness drift. Doodling at a position in the difference domain produces a persistent brightness offset to the right of that position in the restored row, intuitively demonstrating the error-propagation behavior of the invertible “difference–integrate” operation pair.

    3. Core Implementation Details

    3.1 Acquiring and Managing Pixel Data

    After obtaining the RGBA pixel array via Canvas’s getImageData, it is recommended to first convert it to a single-channel floating-point grayscale matrix using the industry-standard luminance weighting:

    1. function toGray(data, w, h) {
    2. const g = new Float64Array(w * h);
    3. for (let i = 0; i < w * h; i++) {
    4. g[i] = 0.299 * data[i * 4] + 0.587 * data[i * 4 + 1] + 0.114 * data[i * 4 + 2];
    5. }
    6. return g;
    7. }

    Using Float64Array or Float32Array to store transform-domain data avoids the boxing overhead of regular arrays and ensures numerical precision.

    3.2 Engineering a 2D FFT

    Directly computing the DFT has O(N⁴) complexity, which is completely infeasible in a browser. The correct approach is to implement a radix-2 Fast Fourier Transform (FFT): perform a 1D FFT along the rows, then a 1D FFT along the columns of the result, reducing total complexity to O(N²·logN). Practical recommendations:

    • Crop or zero-pad the input image to a power-of-two size (e.g., 256×256 or 512×512);
    • Store the real and imaginary parts of complex numbers in two separate real-valued arrays to avoid the memory overhead of object arrays;
    • Use an iterative butterfly computation with precomputed twiddle factors to further reduce trigonometric function calls.
    1. function fft1d(re, im, invert) {
    2. const n = re.length;
    3. for (let i = 1, j = 0; i < n; i++) { // bit-reversal permutation
    4. let bit = n >> 1;
    5. for (; j & bit; bit >>= 1) j ^= bit;
    6. j ^= bit;
    7. if (i < j) {
    8. [re[i], re[j]] = [re[j], re[i]];
    9. [im[i], im[j]] = [im[j], im[i]];
    10. }
    11. }
    12. for (let len = 2; len <= n; len <<= 1) {
    13. const ang = 2 * Math.PI / len * (invert ? -1 : 1);
    14. const wr = Math.cos(ang), wi = Math.sin(ang);
    15. for (let i = 0; i < n; i += len) {
    16. let curR = 1, curI = 0;
    17. for (let k = 0; k < len / 2; k++) {
    18. const uR = re[i + k], uI = im[i + k];
    19. const vR = re[i + k + len / 2] * curR - im[i + k + len / 2] * curI;
    20. const vI = re[i + k + len / 2] * curI + im[i + k + len / 2] * curR;
    21. re[i + k] = uR + vR; im[i + k] = uI + vI;
    22. re[i + k + len / 2] = uR - vR; im[i + k + len / 2] = uI - vI;
    23. const tR = curR * wr - curI * wi;
    24. curI = curR * wi + curI * wr; curR = tR;
    25. }
    26. }
    27. }
    28. if (invert) for (let i = 0; i < n; i++) { re[i] /= n; im[i] /= n; }
    29. }

    3.3 Designing the Doodle Interaction

    The doodle layer uses a mask array matching the size of the transform domain to record the positions covered by the brush. On each mouse move, it iterates over the pixels within the brush radius around the current coordinate and modifies the corresponding transform-domain data according to the selected strategy (zeroing, averaging, or adding random perturbation), then triggers the inverse transform and refreshes the result display. To avoid stuttering from high-frequency recomputation, use requestAnimationFrame for throttling, merging multiple modifications during continuous painting into a single computation per frame.

    3.4 Displaying the Restoration Result

    The floating-point pixel values produced by the inverse transform need to be remapped to the 0–255 display range. Frequency-domain restoration results should first take the real part (or modulus), then be normalized and stretched according to the image’s min/max values to ensure observable contrast. A three-panel view—“original / doodled transform domain / restored image”—should be kept so users can compare and analyze the results.

    4. Performance and UX Optimization Suggestions

    1. Limit computation size: in demo scenarios, uniformly scale the image to 256 or 512 pixels per side, which preserves visual quality while allowing the FFT to complete in milliseconds;
    2. Numerical stability: check the determinant or condition number before matrix inversion, and keep normalization coefficients consistent in frequency-domain operations to avoid brightness drift after round-trip forward/inverse transforms;
    3. Offload heavy computation: for larger images, move the FFT and matrix operations into a Worker thread to avoid blocking the UI;
    4. Interaction details: provide brush size adjustment, doodle undo, and one-click reset, and support touch events for mobile devices.

    5. Conclusion and Extensions

    The web tool described in this article implements five “transform–doodle–restore” experiment modes using pure front-end technology, combining Canvas pixel manipulation, 2D FFT, matrix inversion, and difference–integration techniques. Its value lies not only in the demonstration itself but also in turning abstract frequency-domain and linear algebra concepts into interactive, observable experimental subjects. On this foundation, many extensions are possible, such as frequency-domain filter design demos, image watermark embedding and robustness verification, and distortion analysis of transform-domain compression. If you want to offer such a tool as an online service, you can host the static page resources on an object storage service and pair it with logging and monitoring/alerting capabilities to publish and operate it at low cost.