Frequency-Domain Painting and Image Reconstruction with JavaScript
Build a browser-based image editor that lets users paint on transformed image data and reconstruct the result. This article explains five editing modes, provides JavaScript implementations for FFT-based spectrum editing and row derivatives, and covers display mappings, pointer input, memory limits, Web Workers, and validation.
1. What Does Painting Actually Change?
Many image-processing techniques—including denoising, compression, and style transfer—follow a common pattern: transform an image into another numerical domain, modify the data there, and apply an inverse transform to return to an image.
The browser tool described here makes that workflow interactive:
- Load an image and convert it into a grayscale matrix (I(x, y)), with width (W) and height (H).
- Apply the selected forward transform. Map the resulting data to grayscale values from 0 to 255 for display on a canvas.
- Paint on the canvas using a mouse, touchscreen, or stylus. Painting modifies the underlying numerical data directly; the canvas pixels are only a visualization of that data.
- Click Reconstruct to apply the inverse transform to the edited data and display the resulting image.
Not every mode below operates in the frequency domain. The matrix and row-derivative modes demonstrate the same transform–edit–reconstruct workflow using different representations.
2. The Mathematics Behind Five Editing Modes
All modes use row-major storage, with pixel index:
[
i = yW + x
]
2.1 Invertible Matrix Mode
Flatten the image into a vector (\mathbf{x}) of length (N = WH). Choose an invertible (N \times N) matrix (A), generated using a fixed random seed for repeatable results.
The forward transform is:
[
\mathbf{y} = A\mathbf{x}
]
After the user edits (\mathbf{y}) to produce (\mathbf{y}’), reconstruct the image with:
[
\mathbf{x}’ = A^{-1}\mathbf{y}’
]
Here, (A^{-1}) is the inverse of the transform matrix, computed and stored in advance. Without edits:
[
\mathbf{x}’ = A^{-1}A\mathbf{x} = \mathbf{x}
]
The main limitation is computational cost. For (N = 1024), corresponding to a 32 × 32 grayscale image, (A) and (A^{-1}) each require about 8 MB of storage:
[
1024^2 \times 8\text{ bytes}
]
Computing the inverse with Gauss–Jordan elimination takes on the order of (10^9) floating-point operations. This can be acceptable for a demonstration.
A 64 × 64 image has (N = 4096), requiring about 128 MB per matrix. Inversion becomes expensive enough that processing should run in a Worker, or the mode should enforce a smaller image-size limit.
The transformed values are not restricted to 0–255. Record their minimum and maximum after the forward transform, map that range linearly to grayscale for display, and use the inverse mapping when converting brush values back into numerical values.
2.2 Magnitude Spectrum Mode
Apply a two-dimensional discrete Fourier transform to obtain (F(u, v)), then separate it into magnitude and phase:
[
M = |F|,\qquad P = \arg F
]
Painting changes the magnitude while preserving the phase. Reconstruction uses:
[
F’ = M’e^{iP}
]
followed by the inverse transform.
Magnitude values have a wide dynamic range, so the display uses logarithmic compression:
[
\log(1 + M)
]
Record:
[
\text{maxLog} = \max(\log(1 + M))
]
and use it to map the compressed values to grayscale.
2.3 Phase Spectrum Mode
Preserve the magnitude (M) and edit only the phase (P), whose range is ([-\pi, \pi]).
Phase carries much of an image’s structural information, so changing it can produce pronounced distortions.
2.4 Combined Magnitude and Phase Editing
Maintain separate numerical buffers for magnitude and phase. A toggle in the interface selects the layer being edited.
Reconstruction uses the latest values from both buffers.
2.5 Row-Derivative Mode
Compute horizontal differences:
[
D(x, y) = I(x + 1, y) - I(x, y)
]
for (x = 0, \ldots, W - 2). The displayed derivative image therefore has width (W - 1).
Also save the first pixel of every row:
[
c(y) = I(0, y)
]
Reconstruct each row using:
[
I(x, y) = c(y) + \sum_{k=0}^{x-1}D(k, y)
]
The first column is not editable, so it remains unchanged during reconstruction. Editing a single difference shifts every pixel to its right in the same row by the same amount, before output clipping.
3. Core JavaScript Implementation
3.1 Loading Images and Limiting Their Size
const MAX_SIDE = 512; // Demo limit; adjust for the target devicelet W, H, gray;function loadImage(url) {const img = new Image();// Cross-origin images require server-side CORS headers.// Otherwise, getImageData throws a SecurityError.img.crossOrigin = 'anonymous';img.onload = () => {const scale = Math.min(1, MAX_SIDE / Math.max(img.width, img.height));W = Math.round(img.width * scale);H = Math.round(img.height * scale);canvas.width = W;canvas.height = H;ctx.drawImage(img, 0, 0, W, H);const rgba = ctx.getImageData(0, 0, W, H).data;gray = new Float64Array(W * H);for (let i = 0; i < W * H; i++) {gray[i] = 0.299 * rgba[i * 4] + 0.587 * rgba[i * 4 + 1] + 0.114 * rgba[i * 4 + 2];}};img.src = url;}
The general image limit above is suitable for the spectrum modes, not for the dense matrix mode, which needs a much smaller limit.
3.2 One- and Two-Dimensional FFTs
The following implementation requires each dimension to be a power of two. Zero-pad smaller dimensions to the next power of two, then crop the reconstructed image back to its original size.
function nextPow2(n) {let p = 1;while (p < n) p <<= 1;return p;}function fft1d(re, im, invert) {const n = re.length;for (let i = 1, j = 0; i < n; i++) { // Bit-reversal permutationlet bit = n >> 1;for (; j & bit; bit >>= 1) j ^= bit;j ^= bit;if (i < j) {[re[i], re[j]] = [re[j], re[i]];[im[i], im[j]] = [im[j], im[i]];}}for (let len = 2; len <= n; len <<= 1) {const half = len >> 1;for (let i = 0; i < n; i += len) {for (let j = 0; j < half; j++) {const angle = (invert ? 2 : -2) * Math.PI * j / len;// Compute directly rather than accumulating twiddle-factor error.const cr = Math.cos(angle), ci = Math.sin(angle);const a = i + j, b = a + half;const vr = re[b] * cr - im[b] * ci;const vi = re[b] * ci + im[b] * cr;re[b] = re[a] - vr; im[b] = im[a] - vi;re[a] += vr; im[a] += vi;}}}if (invert) {for (let i = 0; i < n; i++) { re[i] /= n; im[i] /= n; }}}function fft2d(re, im, PW, PH, invert) {const rr = new Float64Array(PW), ri = new Float64Array(PW);for (let y = 0; y < PH; y++) { // Transform rows firstconst off = y * PW;rr.set(re.subarray(off, off + PW));ri.set(im.subarray(off, off + PW));fft1d(rr, ri, invert);re.set(rr, off);im.set(ri, off);}const cr = new Float64Array(PH), ci = new Float64Array(PH);for (let x = 0; x < PW; x++) { // Then transform columnsfor (let y = 0; y < PH; y++) {cr[y] = re[y * PW + x];ci[y] = im[y * PW + x];}fft1d(cr, ci, invert);for (let y = 0; y < PH; y++) {re[y * PW + x] = cr[y];im[y * PW + x] = ci[y];}}}// Swap quadrants to move low frequencies to the center.// For even dimensions, fftshift and ifftshift are identical:// applying this function twice restores the original layout.function shift2d(arr, PW, PH) {const out = new Float64Array(arr.length);const sx = PW >> 1, sy = PH >> 1;for (let y = 0; y < PH; y++) {for (let x = 0; x < PW; x++) {out[((y + sy) % PH) * PW + ((x + sx) % PW)] = arr[y * PW + x];}}return out;}
3.3 Forward Transform for Magnitude and Phase
function forwardSpectrum(gray, W, H) {const PW = nextPow2(W), PH = nextPow2(H);const re = new Float64Array(PW * PH), im = new Float64Array(PW * PH);for (let y = 0; y < H; y++)for (let x = 0; x < W; x++) re[y * PW + x] = gray[y * W + x];fft2d(re, im, PW, PH, false);const mag = new Float64Array(PW * PH), phs = new Float64Array(PW * PH);for (let i = 0; i < mag.length; i++) {mag[i] = Math.hypot(re[i], im[i]);phs[i] = Math.atan2(im[i], re[i]);}// Both display and painting use this centered layout.return {PW,PH,mag: shift2d(mag, PW, PH),phs: shift2d(phs, PW, PH)};}// Paired mappings between numerical values and display grayscale.const magToGray = (m, maxLog) => Math.round(255 * Math.log1p(m) / maxLog);const grayToMag = (g, maxLog) => Math.expm1(g / 255 * maxLog);const phsToGray = (p) => Math.round((p + Math.PI) / (2 * Math.PI) * 255);const grayToPhs = (g) => g / 255 * 2 * Math.PI - Math.PI;
Keep the numerical buffers separate from the rendered image. Display rounding should not overwrite the transform data.
For an all-zero magnitude spectrum, maxLog is zero; handle that case explicitly when rendering to avoid division by zero.
3.4 Painting with Pointer Events
Pointer Events support mouse, touch, and stylus input through the same handlers. Set touch-action: none in the canvas CSS to prevent page scrolling while painting.
let editBuf; // Active numerical buffer, in display layoutlet brushRadius = 6;let brushValue = 0; // Brush value already converted to the numerical domainlet painting = false;function paintAt(buf, dw, dh, cx, cy, radius, value) {for (let dy = -radius; dy <= radius; dy++) {for (let dx = -radius; dx <= radius; dx++) {if (dx * dx + dy * dy > radius * radius) continue;const x = cx + dx, y = cy + dy;if (x < 0 || y < 0 || x >= dw || y >= dh) continue;buf[y * dw + x] = value;}}}function stroke(e, dw, dh, toGray) {const rect = canvas.getBoundingClientRect();const cx = Math.floor((e.clientX - rect.left) * dw / rect.width);const cy = Math.floor((e.clientY - rect.top) * dh / rect.height);paintAt(editBuf, dw, dh, cx, cy, brushRadius, brushValue);renderBuffer(editBuf, dw, dh, toGray);}function renderBuffer(buf, dw, dh, toGray) {const img = ctx.createImageData(dw, dh);for (let i = 0; i < dw * dh; i++) {const g = toGray(buf[i]);img.data[i * 4] = img.data[i * 4 + 1] = img.data[i * 4 + 2] = g;img.data[i * 4 + 3] = 255;}ctx.putImageData(img, 0, 0);}canvas.addEventListener('pointerdown', (e) => {painting = true;canvas.setPointerCapture(e.pointerId);snapshotForUndo(editBuf); // Save a copy before each stroke; see Section 5stroke(e, canvas.width, canvas.height, currentToGray);});canvas.addEventListener('pointermove', (e) => {if (painting) stroke(e, canvas.width, canvas.height, currentToGray);});canvas.addEventListener('pointerup', () => { painting = false; });
Convert the brush’s grayscale value into the relevant numerical domain before painting. For magnitude editing:
brushValue = grayToMag(brushGray, maxLog);
Writing a value from 0 to 255 directly into the magnitude buffer can produce values far below the intended magnitude.
3.5 Reconstructing the Image
For spectrum modes, undo the centering shift, rebuild the complex spectrum from magnitude and phase, and apply the inverse transform. The implementation below retains the real component.
function restoreSpectrum(mag, phs, PW, PH, W, H) {const m = shift2d(mag, PW, PH); // Undo fftshiftconst p = shift2d(phs, PW, PH);const re = new Float64Array(PW * PH), im = new Float64Array(PW * PH);for (let i = 0; i < re.length; i++) {re[i] = m[i] * Math.cos(p[i]);im[i] = m[i] * Math.sin(p[i]);}fft2d(re, im, PW, PH, true);// Edits may break conjugate symmetry, producing an imaginary component.// This implementation discards that component.const out = new Uint8ClampedArray(W * H); // Round and clamp to 0–255 on assignmentfor (let y = 0; y < H; y++)for (let x = 0; x < W; x++) out[y * W + x] = re[y * PW + x];return out;}function rowDerivative(gray, W, H) {const D = new Float64Array((W - 1) * H), c = new Float64Array(H);for (let y = 0; y < H; y++) {c[y] = gray[y * W];for (let x = 0; x < W - 1; x++) {D[y * (W - 1) + x] = gray[y * W + x + 1] - gray[y * W + x];}}return { D, c };}function integrateRows(D, c, W, H) {const out = new Uint8ClampedArray(W * H);for (let y = 0; y < H; y++) {let acc = c[y]; // Keep accumulation in floating point; clamp only on outputout[y * W] = acc;for (let x = 0; x < W - 1; x++) {acc += D[y * (W - 1) + x];out[y * W + x + 1] = acc;}}return out;}
For row derivatives, the display range is −255 to 255. Map it to grayscale with:
Math.round((d + 255) / 2)
Set the editing canvas width to W - 1.
4. Common Questions and Troubleshooting
How Do Magnitude and Phase Differ?
Magnitude determines the strength of each frequency component, primarily affecting brightness distribution and texture contrast.
Phase determines the relative spatial alignment of those components, strongly affecting outlines and image structure. The same brush stroke usually causes more obvious distortion when applied to phase.
Why Does the Image Become Dark or Distorted?
- Overall darkening: In the centered spectrum, the DC component is at index
(PH / 2) * PW + PW / 2for even padded dimensions. Reducing its magnitude lowers the image’s mean brightness. Editing nearby low frequencies can also alter broad brightness patterns. - Warping or distortion: This is an expected consequence of phase editing.
- Unexpected noise or stripes: Check the numerical mappings, particularly that magnitude conversion pairs
log1pwithexpm1. A correctly rendered grayscale pipeline should not introduce colored pixels.
Why Does Reconstruction Differ Before Any Painting?
Without edits, the maximum difference should normally remain within one grayscale level, due to output rounding.
If the difference is larger, check the following:
- Was
shift2dapplied once after the forward transform and once before the inverse transform? - Was the zero-padded region cropped away?
- Are the display mappings paired with the correct inverse mappings?
- Were the original numerical buffers preserved rather than replaced with rounded display values?
For matrix mode, numerical accuracy also depends on the selected matrix and its inversion.
5. Performance, Memory, and Data Handling
Memory Requirements
A 512 × 512 grayscale image contains 262,144 samples. One Float64Array of that size uses about 2 MB.
Spectrum editing requires magnitude and phase buffers, complex working buffers, and undo snapshots. With a modest number of snapshots, the total can reach the low tens of megabytes. Memory use grows with the number of undo states retained.
At 4096 × 4096, a single array occupies about 128 MB. Multiple working arrays can easily make the browser unresponsive or exhaust available memory. Resize large images before processing.
Moving Work to a Web Worker
ImageData itself is not transferable, but its underlying ArrayBuffer is. Transferring a buffer detaches it on the sending side, so the main thread can no longer read or write that buffer. Save copies of any data that must remain available.
// Main threadconst midBuf = mag.slice().buffer; // Preserve a magnitude copy before transferworker.postMessage({ type: 'restore', PW, PH, W, H, mag: mag.buffer, phs: phs.buffer },[mag.buffer, phs.buffer]);worker.onmessage = (e) => {const out = new Uint8ClampedArray(e.data.out);ctx.putImageData(new ImageData(out, W, H), 0, 0);};
This message handler assumes the Worker returns an RGBA buffer containing W * H * 4 elements. The reconstruction function shown earlier returns a single-channel grayscale buffer, so it must be expanded to RGBA before being passed to ImageData.
The transfer also detaches phs.buffer; preserve a phase copy as well if the main thread still needs it.
Undo
Save a copy of the active numerical buffer before each stroke. Keep at most 20 undo states, discarding the oldest when the limit is exceeded.
Undo must restore both the data and its rendered view.
PNG Export
Allow users to export the reconstructed image as a PNG so that refreshing the page does not lose the result. Use canvas.toBlob to generate the file and trigger a download.
Automatic Reconstruction Delay
Make the delay between finishing a stroke and automatic reconstruction configurable.
The appropriate delay depends on the device and image dimensions. Measure reconstruction time on the target device with performance.now() before choosing a value.
6. Validation Checklist
- Unedited reconstruction: In all five modes, the maximum difference from the source grayscale image should be no greater than one grayscale level.
- Non-power-of-two dimensions: Test an image such as 300 × 200 to verify zero-padding and cropping.
- Cross-origin loading: Confirm that no
SecurityErroroccurs. If the image server does not support the required CORS access, show a clear error message. - Undo: Paint one stroke, then undo it. Both the numerical buffer and the displayed image should return to their previous state.
- Export: Verify that the exported PNG dimensions match the reconstructed image.
7. Conclusion
The central workflow is simple: apply a forward transform, edit the intermediate data, and reconstruct with the inverse transform.
A reliable implementation depends on three details:
- Pair numerical-to-display mappings with the correct inverse mappings.
- Apply the centering shift on both sides of the spectrum-editing workflow.
- Paint into numerical buffers, not merely into displayed pixels.
These principles also provide a foundation for extending the editor to other representations, such as wavelet transforms or the discrete cosine transform.
