Transform-Domain Image Doodling with Reversible Restoration: A Web Implementation
This article explains how to build a web page that lets users doodle in an image's transform domain and reversibly restore the original. It covers a five-layer architecture (data, transform, interaction, restoration, rendering), implementation details for five transform modes—invertible matrix transforms, magnitude spectrum, phase spectrum, combined magnitude-phase, and row-derivative editing—plus interaction design, performance strategies, and error control, all with framework-agnostic JavaScript examples.
1. Problem Definition and Design Goals
“Doodle after transforming an image, then restore it” is fundamentally a problem of transform-domain editing with reversible rollback: map the image into an interpretable transform domain, modify coefficients or spectral values with a brush, run the inverse transform to observe the modified image, and—when the user wants to restore—roll back to the pre-edit transform-domain snapshot or the original image snapshot.
The page must satisfy three requirements at once. First, the forward/inverse transform pipeline must be stable, avoiding visual artifacts caused by floating-point error, out-of-range values, or irreversible operations. Second, the doodling interaction must be intuitive enough that users understand whether they are modifying matrix coefficients, magnitude, phase, or a derivative field. Third, the restoration logic must clearly distinguish between two concepts: “inverse-transforming to get the modified result” and “undoing the doodle to recover the original.” The former is a mathematical inverse mapping; the latter is an engineering-level state rollback. Only by combining both can you build an interactive, verifiable experimental page.
This article describes a neutral technical approach with no dependency on any specific third-party framework. The front end can use a standard drawing surface for pixel read/write and brush interaction, while the transform layer is implemented as swappable pure functions, making it easy to plug in faster numerical computation modules later.
2. Overall System Architecture
It is recommended to split the page into five layers:
- Data layer: stores the original image pixels, the current transform-domain cache, the original transform-domain snapshot, the doodle mask, and the undo stack.
- Transform layer: implements the forward transform, inverse transform, normalized visualization, and reversibility checks. Each mode exposes a unified interface, such as
forward(image),inverse(domain), andpaint(domain, mask, brushValue). - Interaction layer: handles brush radius, hardness, doodle value, eraser, undo, and redo. The brush only modifies the region covered by the mask, preventing accidental whole-image changes.
- Restoration layer: provides two actions—“re-run the inverse transform” and “roll back to the snapshot.” The former shows the result of the current doodle; the latter restores the pre-edit state.
- Rendering layer: displays the original image, the transform-domain visualization, the doodled result, and error metrics in a split-screen or overlay layout.
From an engineering standpoint, follow a “snapshot-first” principle: save the original transform-domain data when entering a mode; doodle on a copy; restore the snapshot directly and re-render on rollback. This guarantees users can always roll back, even if a particular transform is not strictly invertible.
3. Principles and Implementation of the Five Transform Modes
3.1 Inverse-Matrix Transform Doodling and Restoration
An image matrix itself is not necessarily invertible, so a more robust interpretation is: apply an invertible linear transform to image blocks or pixel vectors, edit the coefficients in the transform domain, and then reconstruct using the inverse matrix. The implementation must store the transform matrix, the inverse matrix, normalization parameters, and the boundary padding strategy. If the matrix has a large condition number, even a small doodle will be amplified by the inverse transform, so the edit magnitude should be limited, and clipping plus a real-part check should be applied after inversion.
Example code:
function invertMatrix(A) {// Gauss-Jordan elimination for matrix inversion;// production code should add singular-matrix detectionconst n = A.length;const M = A.map((row, i) => [...row,...Array.from({ length: n }, (_, j) => (i === j ? 1 : 0))]);for (let i = 0; i < n; i++) {let p = i;for (let r = i + 1; r < n; r++) {if (Math.abs(M[r][i]) > Math.abs(M[p][i])) p = r;}if (Math.abs(M[p][i]) < 1e-12) throw new Error("Matrix is not invertible");[M[i], M[p]] = [M[p], M[i]];const div = M[i][i];for (let c = 0; c < 2 * n; c++) M[i][c] /= div;for (let r = 0; r < n; r++) {if (r === i) continue;const f = M[r][i];for (let c = 0; c < 2 * n; c++) M[r][c] -= f * M[i][c];}}return M.map(row => row.slice(n));}function matrixModeInverse(domain, AInv) {// domain holds block-wise transform coefficients;// sketch: multiply each block by the inverse matrix and clipreturn domain.map(block => {const out = block.map(() => 0);for (let i = 0; i < block.length; i++) {for (let j = 0; j < block.length; j++) {out[i] += AInv[i][j] * block[j];}}return out.map(v => Math.max(0, Math.min(255, Math.round(v))));});}
3.2 Magnitude Spectrum Doodling and Restoration
After applying a 2D Fourier transform to the image, you obtain a complex spectrum. The magnitude spectrum represents the strength of each frequency component, while the phase spectrum encodes structural position. Magnitude-spectrum doodling typically preserves the phase, modifies the magnitude, then rebuilds the complex spectrum and applies the inverse transform. For visualization, the magnitude should be log-compressed and centered; for reversibility, edits must be applied on a copy of the original magnitude, and restoration must recover the original magnitude snapshot.
function rebuildFromMagPhase(mag, phase) {const re = mag.map((row, y) =>row.map((m, x) => m * Math.cos(phase[y][x])));const im = mag.map((row, y) =>row.map((m, x) => m * Math.sin(phase[y][x])));return { re, im };}function paintMagnitude(mag, mask, value) {return mag.map((row, y) =>row.map((m, x) => (mask[y][x] ? Math.max(0, m + value) : m)));}
3.3 Phase Spectrum Doodling and Restoration
The phase spectrum is highly sensitive to image structure—even a small phase modification can cause noticeable displacement or texture changes. The implementation should wrap phase values into [-π, π] and limit the doodle increment to avoid discontinuities. Restoration likewise relies on the original phase snapshot. Phase doodling is great for demonstrating that “structural information is concentrated in the phase,” but users should be warned that the inverse-transformed result after phase edits may no longer resemble the original image.
3.4 Combined Magnitude and Phase Doodling
The combined mode maintains separate magnitude and phase masks that can be edited independently. During reconstruction, modify the magnitude and phase according to their respective masks, then compose the complex spectrum and apply the inverse transform. This mode carries the most information but is also the most prone to dynamic-range anomalies. It is recommended to display the magnitude map, phase map, and reconstructed result side by side in the UI, and to provide three comparison toggles: “magnitude only,” “phase only,” and “combined.”
3.5 Row-Derivative Doodling and Restoration
Row-derivative mode obtains a horizontal derivative field via finite differences, e.g., dx[y][x] = img[y][x] - img[y][x-1]. After doodling modifies the derivatives, the image can be reconstructed with a cumulative sum: img[y][x] = img[y][x-1] + dx[y][x]. However, the first-column base value of each row must be preserved, otherwise the constant term is lost. This transform is not a strict bijection, so the first-column anchors should be included in the snapshot and restored during rollback.
function forwardRowDerivative(img) {const h = img.length, w = img[0].length;const d = Array.from({ length: h }, () => Array(w).fill(0));for (let y = 0; y < h; y++) {d[y][0] = img[y][0];for (let x = 1; x < w; x++) d[y][x] = img[y][x] - img[y][x - 1];}return d;}function inverseRowDerivative(d, firstCol) {const h = d.length, w = d[0].length;const img = Array.from({ length: h }, () => Array(w).fill(0));for (let y = 0; y < h; y++) {img[y][0] = firstCol[y];for (let x = 1; x < w; x++) img[y][x] = img[y][x - 1] + d[y][x];}return img.map(row => row.map(v => Math.max(0, Math.min(255, v))));}
4. Interaction, Performance, and Error Control
The doodling interaction should follow a “mask + brush value” approach: pixels the brush passes over are written into the mask, and transform-domain modifications apply only to masked regions. Brush radius, hardness, and increment should all be adjustable. To avoid triggering a full-image inverse transform on every mouse move, use a downsampled preview while dragging and recompute at full resolution on release. Large images can be processed in blocks or computed in a background worker.
Error control includes: normalizing inputs to [0,1] or [0,255] before transforming; clipping to the valid range after the inverse transform; detecting singular values in matrix mode; checking for NaN and infinity in Fourier modes; preserving first-column anchors in derivative mode; and pushing to the undo stack before every edit. General metrics such as PSNR and SSIM can be provided to compare the restored result against the original image, but no specific performance figures should be fabricated.
5. Conclusion
The core of this web page is not any single algorithm, but the complete pipeline of “transform-domain visualization + mask-based editing + snapshot rollback + inverse-transform verification.” The inverse-matrix mode emphasizes linear invertibility and numerical stability; the magnitude and phase spectrum modes emphasize frequency-domain decomposition and reconstruction; the row-derivative mode emphasizes integral reconstruction and boundary anchors. Unifying these modes under a single state-management and interaction framework yields an extensible, comparable, and restorable experimental page for transform-domain image doodling.
