JavaScript Image Transform, Doodle, and Restore: A Practical Guide

    This article explains how to build a browser-based pipeline that transforms an image into an editable domain, lets users doodle on the transformed data, and then reconstructs the image through an inverse transform. It covers the overall architecture and data flow, inverse-matrix doodling, magnitude and phase spectrum editing, row-derivative doodling with integration-based recovery, and the interaction, performance, and verification practices needed to keep results stable and reproducible. Readers will find working JavaScript snippets and a clear principle—keep data in floating point internally, map only for display, and never quantize before the inverse transform—that keeps all five modes reliable on a single page.

    Implementing “transform an image, doodle on it, then restore it” in the browser is essentially about mapping an image from the pixel domain into an editable transform domain, allowing the user to modify the transform-domain data, and then returning to the pixel domain through an inverse transform. This kind of page is well suited for teaching demos, algorithm visualization, and interactive experiments. To keep results stable and reproducible, you need to handle four layers at once: mathematical invertibility, numerical normalization, display mapping, and interaction performance. The following is a complete technical approach.

    1. Overall Architecture and Data Flow

    A recommended pipeline is: original-image cache → forward transform → transform-domain visualization → doodle editing → inverse transform → result rendering. Keep the original image in a floating-point array so you do not have to re-quantize it every time you display a step. The forward transform outputs a complex or real matrix in the transform domain; the visualization module is only responsible for mapping the transform domain into a drawable range; the doodle module modifies the transform-domain array directly; the inverse transform rebuilds pixels from the modified array. During rendering, apply clipping and color-space conversion uniformly at the end.

    A core data structure can be designed as:

    1. const state = {
    2. width: 0,
    3. height: 0,
    4. channels: 3,
    5. original: null, // Float32Array, range 0~1
    6. transformed: null, // floating-point data in the transform domain
    7. edited: null, // transform-domain data after doodling
    8. mode: 'matrix' // matrix | magnitude | phase | both | rowDiff
    9. };

    Each channel is processed independently, and the three RGB channels share the same set of transform parameters. For a matrix transform, the transform matrix must be invertible; for frequency-domain transforms, the complete complex information must be preserved; for the row derivative, the boundary row must be preserved. The display layer only performs mapping and must not modify the internal floating-point data, otherwise invertibility is broken.

    2. Inverse-Matrix Doodling and Restoration

    The inverse-matrix mode treats the image as a matrix (X), chooses an invertible matrix (A), and computes (Y=AX). The user doodles on (Y) to obtain (Y’), and restoration computes (X’=A^{-1}Y’). The key to this mode is that the matrix size matches the image size and that (A) is not close to singular. In practice, you should run a condition-number check or an inversion-failure check on (A), and prompt the user to pick a different matrix if it fails.

    Sample code:

    1. function invertMatrix(A) {
    2. const n = A.length;
    3. const M = A.map((row, i) => [
    4. ...row,
    5. ...Array.from({ length: n }, (_, j) => (i === j ? 1 : 0))
    6. ]);
    7. for (let col = 0; col < n; col++) {
    8. let pivot = col;
    9. for (let r = col + 1; r < n; r++) {
    10. if (Math.abs(M[r][col]) > Math.abs(M[pivot][col])) pivot = r;
    11. }
    12. if (Math.abs(M[pivot][col]) < 1e-10) return null;
    13. [M[col], M[pivot]] = [M[pivot], M[col]];
    14. const p = M[col][col];
    15. for (let j = 0; j < 2 * n; j++) M[col][j] /= p;
    16. for (let r = 0; r < n; r++) {
    17. if (r === col) continue;
    18. const f = M[r][col];
    19. for (let j = 0; j < 2 * n; j++) M[r][j] -= f * M[col][j];
    20. }
    21. }
    22. return M.map(row => row.slice(n));
    23. }
    24. function applyMatrix(X, A) {
    25. const n = X.length;
    26. const Y = Array.from({ length: n }, () => new Float32Array(n));
    27. for (let i = 0; i < n; i++) {
    28. for (let j = 0; j < n; j++) {
    29. let s = 0;
    30. for (let k = 0; k < n; k++) s += A[i][k] * X[k][j];
    31. Y[i][j] = s;
    32. }
    33. }
    34. return Y;
    35. }

    When displaying (Y), apply a normalization mapping—for example, find the minimum and maximum first, then linearly map to 0~255. But the inverse transform after doodling must use the floating-point-domain data, not the 8-bit data shown on screen. If a doodle value falls outside the display range, you can allow the internal value to exceed the range and clip only at final rendering.

    3. Magnitude Spectrum, Phase Spectrum, and Joint Doodling

    The 2D discrete Fourier transform maps an image to a complex matrix (F=Re+iIm). The magnitude is (|F|) and the phase is (\arg(F)). The magnitude spectrum is usually displayed with a logarithmic mapping, (\log(1+|F|)); otherwise the dynamic range is too large. When the user doodles on the magnitude spectrum, the displayed value must be converted back to the actual magnitude through the fixed mapping, the original phase is kept, the complex spectrum is rebuilt, and the inverse transform is applied. The phase spectrum can be mapped to grayscale or hue; after doodling, keep the original magnitude and rebuild the complex spectrum.

    Sample flow:

    1. function dft2d(real, imag, inverse = false) {
    2. // Separable implementation: apply a 1D DFT to each row, then to each column
    3. // 1D butterfly details omitted here; returns { re, im }
    4. }
    5. function rebuildFromMagnitudePhase(re, im, newMag, newPhase) {
    6. const outRe = new Float32Array(re.length);
    7. const outIm = new Float32Array(im.length);
    8. for (let i = 0; i < re.length; i++) {
    9. const m = newMag ? newMag[i] : Math.hypot(re[i], im[i]);
    10. const p = newPhase ? newPhase[i] : Math.atan2(im[i], re[i]);
    11. outRe[i] = m * Math.cos(p);
    12. outIm[i] = m * Math.sin(p);
    13. }
    14. return { re: outRe, im: outIm };
    15. }

    The joint doodling mode modifies magnitude and phase at the same time. It is recommended to provide two canvases with synchronized zoom in the UI; when the user edits either canvas, rebuild the preview immediately, but the preview can be downsampled to reduce the computational load. For frequency-domain modes, note that the DC component and low-frequency region have a large effect on overall brightness, so protect the low frequencies when doodling the magnitude or provide a reset button.

    4. Row-Derivative Doodling and Integration-Based Restoration

    The row-derivative mode applies a forward difference to each row: (D[r][c]=I[r][c]-I[r-1][c]), with the first row storing the original value directly. After the user doodles on (D), reconstruction is done by accumulation: (I’[r][c]=I’[r-1][c]+D’[r][c]). This mode is strictly invertible only if the first row is not modified nonlinearly and the integration uses floating-point data. When displaying the derivative, an offset or normalization is usually needed; otherwise negative values are invisible.

    1. function forwardRowDiff(img) {
    2. const out = img.map(row => new Float32Array(row.length));
    3. for (let r = 0; r < img.length; r++) {
    4. for (let c = 0; c < img[0].length; c++) {
    5. out[r][c] = r === 0 ? img[r][c] : img[r][c] - img[r - 1][c];
    6. }
    7. }
    8. return out;
    9. }
    10. function inverseRowDiff(diff) {
    11. const out = diff.map(row => new Float32Array(row.length));
    12. for (let r = 0; r < diff.length; r++) {
    13. for (let c = 0; c < diff[0].length; c++) {
    14. out[r][c] = r === 0 ? diff[r][c] : out[r - 1][c] + diff[r][c];
    15. }
    16. }
    17. return out;
    18. }

    Doodling the derivative can cause integration drift, so keep the floating-point result internally and clip to 0~1 only at render time. If you want strict invertibility, make the first row read-only or provide a separate editing entry point for it.

    5. Interaction, Performance, and Acceptance Criteria

    The interaction layer should provide mode switching, brush size, undo, reset, an original-image comparison, and an error indicator. For performance, the matrix transform has a complexity of (O(n^3)), and a separable 2D DFT can significantly reduce the computation; for large images, preview at a downsampled resolution first and compute the final result at full resolution. The computation can be placed in a Web Worker to avoid blocking drawing. During acceptance, check at least the following: whether the restoration error for an identity transform is close to zero; whether a single-point doodle affects only the expected region; whether the first row and boundaries are correct; whether the RGB channels are consistent; whether reset restores the original image; and whether continuous doodling introduces cumulative quantization error. As long as you stick to the principle of “floating point internally, mapping for display, no quantization before the inverse transform,” all five modes can run stably on the same page with good explainability.