Image Transform Doodling and Reconstruction in Pure JavaScript: Five Modes from Frequency Domain to Derivatives

    Learn how to build a pure front-end image editing pipeline that lets users doodle in a transform domain—inverse matrix transforms, magnitude spectrum, phase spectrum, combined magnitude-phase, and row derivatives—and reconstruct the edited image via inverse transforms. Covers architecture, data flow, coordinate mapping, and numerical stability practices.

    1. Background and Design Goals

    In typical image editing, users draw directly in pixel space. However, many image processing problems are better observed and modified in a transform domain: adjusting spectral components, inspecting phase changes, or editing gradient information, then mapping back to image space via an inverse transform. This article walks through a pure front-end page that loads an image, applies a selected transform to map it onto an editable transform-domain canvas, lets the user doodle over the transformed image, merges the edits back into the transform data, runs the inverse transform, and displays the reconstructed image.

    The page supports five modes: doodling and reconstruction after an inverse-matrix image transform, magnitude spectrum, phase spectrum, simultaneous magnitude and phase editing, and row derivatives. The design goal is not simply layering filters, but building a generic pipeline—forward transform, visualization, interactive editing, data merging, inverse transform, and rendering—so that all modes share the same interaction and state management logic.

    2. Overall Architecture and Data Flow

    The page can be split into four layers:

    1. Image loading and pixel layer: Read an image through a file input, draw it onto an offscreen canvas, use getImageData to fetch RGBA data, and convert it into a grayscale floating-point matrix. Floating-point matrices make subsequent linear transforms, Fourier transforms, and differentiation straightforward.
    2. Transform layer: Each mode provides two pure functions, forward and inverse. forward outputs the transform-domain data plus a visualization matrix for display; inverse takes the edited transform-domain data and produces a reconstructed image matrix.
    3. Interaction layer: Maintain a doodle mask the same size as the display canvas. When the user paints, only the mask and an “edited copy” of the transform-domain data are modified—the original transform data stays intact, which makes undo and mode switching easy.
    4. Rendering layer: Normalize the transform-domain visualization matrix to 0–255 for rendering; clip the reconstructed matrix and convert it back to RGBA. Display normalization must be decoupled from the real data to prevent numeric drift caused by automatic rescaling while the user draws.

    A state object can be designed as follows:

    1. const state = {
    2. mode: 'magnitude',
    3. gray: null, // Float64Array, original grayscale data
    4. transformed: null, // real transform-domain data
    5. display: null, // normalized display data
    6. editMask: null, // Uint8Array, doodle mask
    7. edited: null, // edited copy of transform-domain data
    8. history: []
    9. };

    On every brush movement, set the covered region to 1 in editMask and write the user’s chosen color or value into the corresponding positions in edited. When the user clicks “Reconstruct,” run the inverse transform on edited—not on display, which is only a visualization.

    3. Implementing the Five Transform Modes

    3.1 Inverse Matrix Transform: Doodling and Reconstruction

    Here “inverse matrix” means: first apply an invertible linear or affine transform to the image to obtain a transformed image; the user doodles on it; then an inverse matrix maps the edited result back to the original image space. Common approaches include applying an invertible matrix transform to pixel coordinates, or an invertible linear combination of color channels. Coordinate transforms require handling interpolation, boundary conditions, and singular matrices.

    Let the forward transform matrix be M and the inverse matrix be M^-1. For each output pixel coordinate (x, y), sample the source image via inverse mapping; after editing, map the transformed image back with M^-1. If the matrix determinant is close to zero, reject the matrix and report that it is not invertible. Start by implementing a 3×3 affine matrix inversion:

    1. function invert3x3(m) {
    2. const [a,b,c,d,e,f,g,h,i] = m;
    3. const det = a*(e*i-f*h) - b*(d*i-f*g) + c*(d*h-e*g);
    4. if (Math.abs(det) < 1e-12) throw new Error('Matrix is not invertible');
    5. return [
    6. (e*i-f*h)/det, (c*h-b*i)/det, (b*f-c*e)/det,
    7. (f*g-d*i)/det, (a*i-c*g)/det, (c*d-a*f)/det,
    8. (d*h-e*g)/det, (b*g-a*h)/det, (a*e-b*d)/det
    9. ];
    10. }

    When merging doodles, brush coordinates from the display must be mapped to transform-domain data coordinates. If the display canvas is scaled, use a unified coordinate conversion function to ensure brush positions align with data indices. During reconstruction, apply the inverse mapping to the edited transformed image, and fill empty regions with edge replication or transparency to avoid black borders.

    3.2 Magnitude Spectrum: Doodling and Reconstruction

    Apply a 2D discrete Fourier transform to the grayscale image to obtain the complex spectrum F(u,v). The magnitude spectrum is |F| and the phase spectrum is arg(F). The magnitude spectrum typically has a very large dynamic range, so apply logarithmic compression for display:

    1. display = Math.log(1 + magnitude) / Math.log(1 + maxMagnitude) * 255;

    The user’s doodles modify magnitude values; during the inverse transform, the original phase must be preserved and only the magnitude replaced. In the magnitude spectrum, low frequencies generally correspond to overall brightness and contours, while high frequencies correspond to edges and details. Doodling in low-frequency regions can significantly change brightness distribution; doodling in high-frequency regions can enhance or suppress detail. To prevent the inverse transform result from overflowing, clamp the edited magnitude to a reasonable range, or clip uniformly after the inverse transform.

    3.3 Phase Spectrum: Doodling and Reconstruction

    Phase spectrum display usually maps [-π, π] to 0–255. The user’s doodles modify the phase; during the inverse transform, the original magnitude is preserved. Phase is highly sensitive to image structure—local phase edits can cause visible shifts, texture distortion, or ringing. When implementing, denormalize the display value back to radians, then combine it with the original magnitude into a complex number:

    1. const editedPhase = displayToPhase(editedDisplay);
    2. const re = magnitude * Math.cos(editedPhase);
    3. const im = magnitude * Math.sin(editedPhase);

    Phase editing must guard against display discontinuities caused by atan2 branch jumps. The display layer can apply phase unwrapping or use a cyclic colormap, but the real data should still be stored in radians.

    3.4 Simultaneous Magnitude and Phase Editing

    The combined mode lets users edit magnitude and phase at the same time. You can offer two switchable editing channels, or display two canvases side by side. The data layer stores two matrices, magnitude and phase, and doodling updates the matrix for the current channel. Reconstruction combines them into a complex spectrum and runs the inverse Fourier transform. This mode is the most flexible but also the most likely to produce unpredictable results, so provide controls such as “edit current channel only,” “reset channel,” and “undo.”

    3.5 Row Derivatives: Doodling and Reconstruction

    The row derivative mode applies a first-order difference along each row, e.g. d[x] = gray[x+1] - gray[x]. The derivative image can be displayed as signed grayscale or pseudo-color. After the user edits the derivative, reconstruction requires a cumulative sum along each row. The key issue is the integration constant: a first-order derivative loses each row’s constant offset. A common approach is to keep each row’s first pixel or row mean from the original image as the integration starting point, then accumulate the edited derivative. Without this, the reconstructed image will exhibit overall brightness drift.

    1. function integrateRows(deriv, firstColumn) {
    2. const out = new Float64Array(deriv.length);
    3. for (let y = 0; y < height; y++) {
    4. out[y * width] = firstColumn[y];
    5. for (let x = 1; x < width; x++) {
    6. out[y * width + x] = out[y * width + x - 1] + deriv[y * width + x];
    7. }
    8. }
    9. return out;
    10. }

    Doodling in the derivative domain has a cumulative visual effect: a local edit affects all subsequent pixels in that row. The UI should therefore warn the user that “edits propagate forward from the modified point,” and provide reset and local rollback capabilities.

    4. Interaction, Performance, and Correctness Practices

    First, separate display normalization from real data. Transform-domain display often requires logarithmic compression or linear stretching, but the inverse transform must use the real floating-point data. Every doodle should write to a copy of the real data, which is normalized only at render time.

    Second, unify brush coordinates. The display canvas size, CSS size, and data matrix size may all differ, so use ratio-based mapping and rounding to ensure correct brush indices. Brush radius should be computed in data pixels.

    Third, optimize performance. 2D Fourier transforms and matrix transforms can be time-consuming. Use block computation, cache the original transform results, debounce brush movement, or move heavy recomputation into a background thread. For large images, downsample for preview first and compute at full resolution only on export.

    Fourth, ensure numerical stability. Check the determinant before matrix inversion; handle near-zero magnitudes after the Fourier transform to avoid division by zero; clip inverse transform results to 0–255; limit accumulated error during integration-based reconstruction.

    Fifth, support undo and reproducibility. Save a summary of each brush stroke or a transform-domain snapshot to enable undo. Include the mode, matrix parameters, edit mask, and normalization parameters in the state so reconstruction results are reproducible.

    5. Conclusion

    The core value of this page is turning “image transformation” from a one-shot computation into an interactive editing process. The inverse matrix mode emphasizes invertible mapping and spatial consistency; the magnitude and phase spectrum modes highlight the relationship between frequency components and image structure; the combined mode offers freer editing; and the row derivative mode demonstrates constant handling in differentiation and integration-based reconstruction. With a unified transform pipeline, separation of real and display data, disciplined coordinate mapping, and robust inverse-transform validation, you can build a clear, extensible image transform doodling and reconstruction tool entirely in front-end JavaScript.