# JavaScript Image Transform Doodle with Reversible Restoration
This article explains how to build a browser-based image editing tool where users doodle on a transformed representation of an image—an invertible color matrix, Fourier magnitude or phase spectrum, or row-derivative space—and then invert the transform to recover the final image. It covers the mathematical models behind five editable modes, front-end architecture and state design, brush interaction details, and strategies for performance, numerical stability, and testing. Readers will gain a complete blueprint for implementing reversible, real-time image experiments in JavaScript.
1. Problem Background and Overall Goals
“Doodle on a transformed image, then restore it” is a front-end application with value for both visual education and interactive experimentation: first convert the image into a representation space that is easier to observe or edit—for example an invertible matrix space, the frequency-domain magnitude spectrum, the phase spectrum, or a row-derivative space; let the user doodle on that representation; then apply the corresponding inverse transform to obtain the final image. Unlike an ordinary drawing canvas, the key is not “drawing something pretty” but reversibility, data consistency, real-time feedback, and numerical stability.
The requirements can be summarized as five switchable modes:
- Invertible matrix mode: apply an invertible linear transform to each pixel vector, then restore with the inverse matrix;
- Magnitude spectrum mode: modify the magnitude in the Fourier frequency domain while keeping the phase unchanged;
- Phase spectrum mode: modify the phase while keeping the magnitude unchanged;
- Joint magnitude and phase mode: edit both magnitude and phase simultaneously;
- Row-derivative mode: edit the first-order differences along image rows, then restore by integrating row by row.
A complete interactive loop should include: image loading and preprocessing, forward transform, display mapping of the transformed result, brush editing, inverse transform, result composition, export, and reset. All modes share the same state management, coordinate mapping, and undo mechanism, while mode-specific differences are encapsulated in “transform adapters”. This keeps coupling low and makes it easy to add new reversible representations later.
2. Core Mathematical Models of the Five Modes
2.1 Invertible Matrix Mode
Treat each pixel’s RGB channels as a 3D vector. Given an invertible matrix M and the original pixel vector x, the forward result is y = Mx. When the user produces an edit increment d in the transformed domain, the edited vector becomes y’ = y + d, and the restored result is x’ = M⁻¹y’. If M is chosen to be close to the identity matrix, orthogonal, or a well-conditioned mixing matrix, you can preserve visual readability while retaining invertibility. Two engineering points deserve attention:
First, the matrix must be strictly invertible. If the determinant is near zero, the inverse matrix will amplify tiny brush errors into severe noise. Check the determinant at initialization, and in the UI only offer pre-validated preset matrices, or validate user input immediately.
Second, display clipping is not data clipping. Floating-point values after the forward transform may be negative or greater than 1. For display, you can apply gain, offset, or clamping uniformly, but the internal float arrays must be preserved. Restoration must use the unclipped data, mapping to a displayable range only when finally writing to the canvas. Otherwise, even a zero-edit round trip will fail.
A generic 3×3 matrix inversion and per-pixel application skeleton:
function invert3(m) {const [a, b, c, d, e, f, g, h, i] = m;const det =a * (e * i - f * h) -b * (d * i - f * g) +c * (d * h - e * g);if (Math.abs(det) < 1e-8) throw new Error('Matrix not invertible or ill-conditioned');return [(e * i - f * h) / det,(c * h - b * i) / det,(b * f - c * e) / det,(f * g - d * i) / det,(a * i - c * g) / det,(c * d - a * f) / det,(d * h - e * g) / det,(b * g - a * h) / det,(a * e - b * d) / det];}function applyColorMatrix(src, m, reverseM, reverse = false) {const M = reverse ? reverseM : m;const out = new Float32Array(src.data.length);for (let p = 0; p < src.data.length; p += 4) {const r = src.data[p] / 255;const g = src.data[p + 1] / 255;const b = src.data[p + 2] / 255;out[p] = M[0] * r + M[1] * g + M[2] * b;out[p + 1] = M[3] * r + M[4] * g + M[5] * b;out[p + 2] = M[6] * r + M[7] * g + M[8] * b;out[p + 3] = src.data[p + 3] / 255;}return out;}
In a real product, also consider color space, the alpha channel, and display gain. The alpha channel typically does not participate in color mixing; if special handling for transparent pixels is needed, define the strategy clearly during preprocessing to avoid edge halos after doodling.
2.2 Magnitude, Phase, and Joint Frequency-Domain Modes
The core of frequency-domain modes is the 2D discrete Fourier transform. Convert the image luminance (or per-channel data) into complex arrays; after the forward transform you get real parts re and imaginary parts im, from which magnitude and phase are computed:
function toPolar(re, im) {const n = re.length;const mag = new Float32Array(n);const phase = new Float32Array(n);for (let i = 0; i < n; i++) {mag[i] = Math.hypot(re[i], im[i]);phase[i] = Math.atan2(im[i], re[i]);}return { mag, phase };}function fromPolar(mag, phase, re, im) {for (let i = 0; i < mag.length; i++) {re[i] = mag[i] * Math.cos(phase[i]);im[i] = mag[i] * Math.sin(phase[i]);}}
The magnitude spectrum usually has an enormous dynamic range; displaying it linearly leaves only a few bright spots at the center. The display layer therefore commonly uses a logarithmic mapping log(1 + mag) followed by normalization. When the user draws on screen, they modify the log magnitude in the display domain; before writing into internal data, restore it back to linear magnitude using expm1 or an equivalent mapping, and clamp the magnitude to non-negative values. Phase can be displayed as grayscale, a hue wheel, or a banded color scale; regardless of the visualization, internal phase should be stored in radians with periodicity preserved.
The three frequency-domain modes differ in what may be modified:
- Magnitude mode: only mag is edited; phase uses the original values;
- Phase mode: only phase is edited; mag uses the original values;
- Joint mode: both magnitude and phase are editable, usually via two editing layers or switchable brushes, to avoid ambiguous edit semantics on the same pixel.
A frequently overlooked mathematical constraint: the full 2D spectrum of a real-valued image has conjugate symmetry. If you independently modify the magnitude and phase of each frequency bin and then directly invert the transform, the result is generally complex and cannot strictly correspond to a real-valued image. Two practical approaches exist: first, apply consistent edits to paired symmetric frequency bins to maintain conjugate symmetry; second, take the real part of the inverse transform as the final image and state in the UI that this is an approximate projection. The former is more rigorous; the latter is better suited to teaching demonstrations. If the product claims “reversible restoration”, prefer the symmetry-preserving edit strategy, or at least clearly distinguish a “strictly reversible mode” from a “free-editing demo mode”.
Frequency centering must also be handled clearly in coordinate mapping. Display typically shifts low frequencies to the center of the canvas; the canvas coordinate clicked by the user must first be converted to image coordinates and then un-shifted to spectrum array indices. Skipping this step misaligns the brush position relative to the spectral structure.
2.3 Row-Derivative Mode
The row-derivative mode treats each image row as a 1D signal and computes the first-order difference:
function forwardRowDiff(src, w, h) {const diff = new Float32Array(w * h);const first = new Float32Array(h);for (let y = 0; y < h; y++) {const row = y * w;first[y] = src[row];diff[row] = 0;for (let x = 1; x < w; x++) {diff[row + x] = src[row + x] - src[row + x - 1];}}return { diff, first };}
Restoration accumulates along each row, keeping the original first pixel of each row as the boundary condition:
function inverseRowDiff(diff, first, w, h) {const out = new Float32Array(w * h);for (let y = 0; y < h; y++) {const row = y * w;let acc = first[y];out[row] = acc;for (let x = 1; x < w; x++) {acc += diff[row + x];out[row + x] = acc;}}return out;}
Why must the boundary be preserved? Because the derivative only describes the change between adjacent pixels—any constant offset leaves the derivative unchanged. Without each row’s starting value, the restored result drifts as a whole and cannot be uniquely determined. Therefore, the “editable region” in row-derivative mode should explicitly exclude the first pixel of each row, or interpret edits to the first pixel as modifications to the boundary value. For color images processed per channel, each channel needs its own row boundary stored.
3. Front-End Architecture and State Design
The application is best divided into five layers: input, transform, editing, restoration, and presentation. The input layer handles image decoding, resizing, and orientation correction; the transform layer produces only reversible intermediate data; the editing layer stores user brush increments; the restoration layer inverse-transforms “base transform data + increments” back into an image; the presentation layer handles side-by-side views, zooming, coordinate mapping, and accessibility hints.
A possible state structure is shown below. base is the base data after the forward transform and delta is the user’s edit increment; separating the two makes reset and eraser trivial: reset simply zeroes delta, and the eraser writes the increment back to zero instead of “reverse-painting” on already drawn pixels, which would accumulate errors.
const appState = {mode: 'magnitude', // matrix | magnitude | phase | joint | rowDiffsource: null, // normalized floating-point pixelsbase: null, // forward transform resultdelta: null, // user edit incrementsrestored: null, // inverse transform resulthistory: [],generation: 0 // prevents stale async results from overwriting new state};
Each mode implements a uniform interface: forward(source) returns base data and the display mapping; applyStroke(delta, point, brush) writes increments; inverse(base, delta) returns the restored image; renderPreview(data) handles canvas output. Mode switching then cannot pollute the main flow.
Coordinate mapping must uniformly handle CSS size, canvas buffer size, device pixel ratio, and image scaling. Use standard Pointer Events for input: on pointer-down record the start point and capture the pointer; on move convert client coordinates to image coordinates and clamp to the valid range. In row-derivative mode, the first column of each row should be marked as a non-drawable boundary in the UI, or clicks should be internally converted to boundary-value modifications.
4. Key Details of Doodle Interaction
Brushes should not paint colors directly onto base data. A more robust model is the “soft brush increment”: each brush stamp produces a normalized weight—computed from pressure, speed, or a fixed falloff curve—which is multiplied by the target change and accumulated into delta. In matrix mode, increments can be any real number; in magnitude mode, choose one consistent representation (linear or log magnitude) and ensure modified magnitudes stay non-negative; in phase mode, the increment is an angular delta, which can be normalized to the principal interval with atan2(sin θ, cos θ); in row-derivative mode, increments are signed differences that can be displayed with a zero-centered two-color mapping.
For undo and redo, save operation records rather than every intermediate image. A single stroke records mode, brush parameters, path points, and a timestamp; replay recomputes the increments. If frequency-domain arrays are very large, sample path segments and save segment snapshots when precise undo is needed. Because all modes may exhibit floating-point error, acceptance criteria should use tolerances rather than bitwise equality.
The UI should also provide side-by-side views: original image, editable transform-domain view, and restored result view. Users need to see “which space the current brush is operating in”. For the joint frequency-domain mode, clearly indicate whether the brush targets magnitude or phase—for example via two tabs or a current-channel indicator in the canvas corner. In any mode, out-of-range values should be retained internally, clamped only at final output, with a status bar note such as “data exceeds the displayable range”.
5. Performance, Stability, and Testability
First, prefer Float32Array as the data container, avoiding object arrays and frequent garbage collection. The frequency domain needs two arrays—real and imaginary parts—and the base transform result should be cached; while the user moves the brush, only the inverse transform is recomputed, never the forward transform.
Second, throttle recomputation. During pointer movement you can lower the preview resolution or batch work into requestAnimationFrame; after pointer-up, perform the full-resolution restoration. If the 2D Fourier transform is heavy, move it into a Web Worker, use transferable ArrayBuffers to reduce copying, and use a generation counter to cancel stale tasks so old results never overwrite new state.
Third, boundary and numerical checks must come first. Matrix mode checks the determinant and condition number; frequency-domain mode checks that magnitudes are non-negative and phases finite; row-derivative mode accumulates at higher precision before writing to the display array; all modes guard against NaN, Infinity, and extreme values. For images whose frequency-domain dimensions are not powers of two, zero-pad to a suitable size and crop back after the transform—but clearly distinguish “display padding” from “data size” to avoid coordinate misalignment.
Fourth, tests should cover both mathematical properties and interaction paths. Math-side tests include: zero-edit round-trip error, row derivatives of a constant image, frequency-domain characteristics of a single-point impulse, matrix determinant validation, and phase periodicity normalization. Interaction-side tests include: rapid continuous drawing, undo/redo, mode switching, window resizing, touch and stylus input, extremely wide and tall images, and images with transparent backgrounds. For visual regression tests, fix a set of small synthetic images—gradients, checkerboards, a single bright row, isolated bright spots—and generate snapshots of all three views.
Accessibility and usability should also be part of engineering acceptance: mode switches use focusable controls with text descriptions; brush size and reset buttons are keyboard-operable; canvas result changes are announced via a status region; color contrast meets general readability requirements; animations are minimized for motion-sensitive users. If the product emphasizes privacy, the UI can explicitly state that image processing happens locally in the browser and original images are never uploaded.
6. Conclusion
“Doodle on a transformed image, then restore it” looks like a drawing app, but it is actually a comprehensive exercise in reversible transforms, floating-point data management, frequency-domain visualization, and interactive real-time performance. Three principles should always hold during implementation: separate the base transform from user increments; separate display mapping from internal data; and make each mode’s inverse transform formula and boundary conditions verifiable. Matrix mode focuses on matrix conditioning; frequency-domain modes focus on magnitude/phase representation and the real-valued constraint; row-derivative mode focuses on each row’s boundary value. Combined with a unified state machine, throttled recomputation, replayable brush operations, and tests covering mathematical properties, you can build a logically rigorous, extensible, browser-based image experimentation tool well suited to both teaching demonstrations and engineering practice.
