Building a JavaScript Web App for Image Transform Doodling and Restoration
This article explains how to build a web-based tool using JavaScript that allows users to apply reversible transforms to an image, doodle in the transform domain, and restore the modified image. It covers five transform modes, system architecture, interaction design, and performance optimization strategies.
Building a JavaScript Web App for Image Transform Doodling and Restoration
1. Problem Definition & Design Goals
An image is essentially a two-dimensional numerical matrix in a computer. By applying an invertible transform to an image, “doodling” in the transform domain—locally modifying the transform coefficients—and then executing the inverse transform, you can obtain a modified restored image. In this process, the original image remains unchanged; changes occur in the transform domain, making it highly suitable for visual teaching, signal processing demonstrations, and image editing experiments.
A complete web implementation typically needs to meet the following goals:
- Five Switchable Transform Modes: Inverse matrix transform, magnitude spectrum, phase spectrum, joint magnitude and phase, and row derivative.
- Transform Domain Visualization: Map coefficients to drawable grayscale or pseudo-color images, allowing users to doodle with a brush.
- Invertible Restoration: The doodled coefficients must be able to return to the image space through the corresponding inverse transform.
- Real-time Interactive Control: Support brush size, clearing doodles, resetting, undoing, and result comparison.
- Numerical Safety: Handle floating-point errors, phase wrapping, pixel clipping, and NaN protection.
It should be emphasized that the restored result after doodling is not guaranteed to match the original image because the transform domain coefficients have been modified. Invertibility guarantees the mathematical pairing of “transform and inverse transform,” not that the original image can still be restored after arbitrary modifications.
2. Overall Architecture & Data Flow
It is recommended to split the page into four state layers:
- Original Image Data Layer: Stores the original pixel matrix, read-only.
- Transform Domain Layer: Stores the current mode’s transform coefficients and visualization data for display.
- Doodle Mask Layer: Records the locations and amounts of modifications made by the user on the transform domain canvas.
- Restoration Result Layer: Executes the inverse transform on the modified coefficients and writes the result back to the canvas.
The data flow can be summarized as follows:
Original Image -> forward(mode) -> Transform Coefficients -> Visualization -> User Doodling-> Modified Coefficients -> inverse(mode) -> Restored Image -> Result Canvas
Each mode should implement a unified interface:
const transforms = {matrix: {forward(imageData) { /* return coefficients and visualization data */ },inverse(coeff, mask) { /* return ImageData */ }},magnitude: { forward() {}, inverse() {} },phase: { forward() {}, inverse() {} },magnitudePhase: { forward() {}, inverse() {} },rowDerivative: { forward() {}, inverse() {} }};
The benefit of a unified interface is that the interaction layer does not need to care about the specific algorithm; it only needs to call forward and inverse based on the current mode.
3. Principles & Implementation of Five Transform Modes
1. Inverse Matrix Transform Mode
The core of the inverse matrix mode is to select an invertible linear transformation matrix and perform matrix multiplication on image blocks or the whole image. Taking a 2×2 pixel block as an example, let the block vector be b and the transformation matrix be A:
c = A · bb' = A⁻¹ · c
As long as det(A) != 0, the matrix is invertible. The user doodles on the transformed coefficients c, and during restoration, it is multiplied back by A⁻¹. An example matrix could be:
const A = [[1, 0.5], [0.25, 1]];// det = 1*1 - 0.5*0.25 = 0.875, invertible
Sample code:
function forwardMatrixBlock(block, A) {const [a, b, c, d] = A.flat();return [a * block[0] + b * block[1],c * block[0] + d * block[1]];}function inverseMatrixBlock(coeff, A) {const [a, b, c, d] = A.flat();const det = a * d - b * c;const inv = [[d / det, -b / det], [-c / det, a / det]];return [inv[0][0] * coeff[0] + inv[0][1] * coeff[1],inv[1][0] * coeff[0] + inv[1][1] * coeff[1]];}
In actual implementation, pay attention to pixel normalization and clipping. The transformed coefficients may exceed 0~255, so dynamic normalization is required before visualization; after restoration, it must also be clipped to a valid range. If integer quantization is used, the inverse transform will produce rounding errors, which is normal.
2. Magnitude Spectrum Mode
The 2D Discrete Fourier Transform (2D DFT) converts the image from the spatial domain to the frequency domain. The frequency domain result contains magnitude and phase:
F(u,v) = |F(u,v)| · e^{jφ(u,v)}
The magnitude spectrum mode only allows the user to modify the magnitude, preserving the original phase. During display, a logarithm is typically applied to the magnitude to compress the dynamic range:
display = log(1 + |F(u,v)|)
After doodling and modifying the magnitude, the original phase is used to rebuild the complex frequency spectrum, and then the 2D Inverse Fourier Transform is executed. Sample logic:
function rebuildFromMagnitude(mag, phase) {const real = mag * Math.cos(phase);const imag = mag * Math.sin(phase);return { real, imag };}
Magnitude spectrum doodling is often used to observe the impact of frequency energy changes on image texture, edges, and overall brightness. Because phase carries a large amount of structural information, when only the magnitude is modified, the image contour is usually still recognizable, but the texture and contrast will change.
3. Phase Spectrum Mode
The phase spectrum mode preserves the original magnitude and only modifies the phase. Phase values are located in [-π, π] and need to be normalized to the grayscale range for display. After the user doodles, the modified phase is combined with the original magnitude:
function rebuildFromPhase(phase, mag) {return {real: mag * Math.cos(phase),imag: mag * Math.sin(phase)};}
Phase is highly sensitive to image structure. Local phase modifications can cause noticeable displacement, ghosting, or structural disorder. During implementation, pay attention to phase wrapping: the modified phase should be handled naturally through modulo or trigonometric functions, without forcibly limiting it to a fixed interval, because cos and sin are inherently periodic.
4. Joint Magnitude & Phase Mode
The joint mode allows simultaneous modification of magnitude and phase. In implementation, the logic of the previous two modes can be reused to obtain the modified magnitude matrix and phase matrix respectively, and then uniformly rebuild the complex frequency spectrum and perform the inverse transform. This mode offers the most visual freedom but is also the most prone to strong artifacts. Therefore, the interaction layer should provide toggles for “view magnitude only,” “view phase only,” and “view jointly” to facilitate locating the source of modifications.
5. Row Derivative Mode
The row derivative mode applies a horizontal finite difference to the image:
D(x,y) = I(x,y) - I(x-1,y)
Where the boundary column can be defined as I(0,y) or 0. The inverse transform is restored through accumulation:
I(x,y) = D(x,y) + I(x-1,y)
Sample code:
function forwardRowDerivative(image, width, height) {const out = new Float32Array(width * height);for (let y = 0; y < height; y++) {for (let x = 0; x < width; x++) {const i = y * width + x;const left = x > 0 ? image[i - 1] : 0;out[i] = image[i] - left;}}return out;}function inverseRowDerivative(deriv, width, height) {const out = new Float32Array(width * height);for (let y = 0; y < height; y++) {let acc = 0;for (let x = 0; x < width; x++) {const i = y * width + x;acc += deriv[i];out[i] = acc;}}return out;}
Row derivative doodling is suitable for demonstrating the relationship between “edge information” and “integral restoration.” Since integration accumulates errors, quantization or large modifications may cause brightness drift, so the results need to be normalized or clipped.
4. Interaction Layer & Visualization Details
The transform domain canvas needs to establish coordinate mapping: the canvas pixel coordinates correspond to the coefficient matrix indices. For spectrum modes, the zero-frequency usually needs to be shifted to the center to help users understand low-frequency and high-frequency regions. When the brush modifies, it should not directly change the display grayscale, but rather record to the coefficient modification layer—for example, saving the delta or mask value—and apply it during the inverse transform.
Recommended interaction states include:
- Current mode;
- Brush radius and intensity;
- Doodle mask;
- Original coefficient cache;
- Restoration result cache;
- Undo stack.
The undo stack can save the rectangular areas affected by each stroke and the coefficients before modification, avoiding memory pressure caused by full-image snapshots.
5. Performance & Reliability Optimization
- Use TypedArrays: Use
Float32ArrayorUint8ClampedArrayfor pixel and coefficient matrices to reduce object allocation. - Cache Transform Results: Cache the
forwardresults when switching modes, and only recalculate affected areas during doodling. - Spectrum Calculation Optimization: 2D DFT can be decomposed into 1D row and column transforms; production implementations can use split-radix FFT and cache twiddle factors.
- Offscreen Drawing: Separate the visualization layer from the interaction layer to reduce main canvas redraws.
- Web Workers: Large image FFTs can be placed in a Worker to avoid blocking the UI.
- Numerical Protection: Check for NaN and Infinity before the inverse transform; perform finite value clipping on magnitude and phase; execute
clamp(0,255)before writing results back. - Invertibility Test: Execute
inverse(forward(x))on un-doodled data and compare the error with the original matrix; the error should be within floating-point tolerance.
6. Acceptance & Conclusion
During acceptance, coverage should include: the five modes can switch normally; the inverse transform result without doodling approximates the original image; the doodled result is visible and does not crash; clearing and resetting restore the initial state; large image operations do not cause noticeable lag; and no uncaught exceptions appear in the console. By unifying the transform interface, establishing a clear doodle mask, and implementing a stable inverse transform, you can build a well-structured and extensible JavaScript web page for image transform doodling and restoration.
