Frequency-Domain Image Drawing and Reversible Reconstruction with JavaScript and Canvas

    Learn how to build a browser-based image editing experiment that transforms images into the frequency domain, lets users draw directly on magnitude and phase spectra or derivative images, and reconstructs the modified image through inverse transforms. Covers 2D DFT implementation, spectrum visualization, complex spectrum recovery, Canvas interaction, and performance optimization in plain JavaScript.

    Introduction

    Image editing typically operates directly on pixels — modifying color, brightness, or local texture in the spatial domain. However, an image can also be mapped into other representation spaces through mathematical transforms, such as the frequency domain, the gradient domain, or a linear transform domain. In these spaces, the image’s structural information appears in entirely different forms:

    • Low-frequency components generally contain overall brightness, contours, and slowly varying regions;
    • High-frequency components correspond to edges, details, textures, and noise;
    • The magnitude spectrum describes the strength of different frequency components;
    • The phase spectrum describes how those frequency components are arranged spatially;
    • Derivative images highlight locations where pixel values change sharply.

    This article walks through a browser-side experiment page that supports five types of operations:

    1. Drawing on the transform result and applying the inverse transform;
    2. Drawing on the magnitude spectrum and attempting reconstruction;
    3. Drawing on the phase spectrum and attempting reconstruction;
    4. Modifying the magnitude and phase spectra simultaneously;
    5. Modifying the image’s horizontal derivative, then reconstructing the image via integration or constrained reconstruction.

    “Reconstruction” here does not guarantee recovering the original image. Once information in the transform domain is modified, the inverse transform will produce a different result. The value of this experiment lies in observing how the image degrades when different types of information are damaged, and which information matters most to visual structure.

    Overall Processing Pipeline

    A complete image processing pipeline can be abstracted as:

    1. Load image
    2. ↓
    3. Draw to Canvas
    4. ↓
    5. Extract grayscale or color channels
    6. ↓
    7. Apply transform
    8. ↓
    9. Map transform result to a visualizable image
    10. ↓
    11. User draws modifications
    12. ↓
    13. Read modified data
    14. ↓
    15. Restore complex or derivative data
    16. ↓
    17. Apply inverse transform
    18. ↓
    19. Display reconstruction result

    In the browser, CanvasRenderingContext2D provides getImageData() to retrieve the pixel array. Each pixel consists of four consecutive values:

    1. R, G, B, A

    The first three are color channels and the last is transparency. To reduce complexity, this experiment first converts color images to grayscale:

    1. function toGray(data, width, height) {
    2. const gray = new Float64Array(width * height);
    3. for (let y = 0; y < height; y++) {
    4. for (let x = 0; x < width; x++) {
    5. const p = (y * width + x) * 4;
    6. const r = data[p];
    7. const g = data[p + 1];
    8. const b = data[p + 2];
    9. gray[y * width + x] =
    10. 0.299 * r + 0.587 * g + 0.114 * b;
    11. }
    12. }
    13. return gray;
    14. }

    Grayscale conversion is not mandatory. To preserve color, you can transform the R, G, and B channels independently, but the computation cost increases significantly, and editing each channel separately may introduce color shifts.

    2D Discrete Fourier Transform

    Complex Representation

    The result of a 2D discrete Fourier transform is not an ordinary real number but a complex number:

    1. F(u, v) = Re(u, v) + i · Im(u, v)

    Where:

    • Re is the real part;
    • Im is the imaginary part;
    • u, v are frequency coordinates;
    • i is the imaginary unit.

    The 2D transform is defined as:

    1. F(u,v) =
    2. ΣΣ f(x,y) · exp[-i2π(ux/W + vy/H)]

    And the inverse transform:

    1. f(x,y) =
    2. 1/(WH) · ΣΣ F(u,v) · exp[i2π(ux/W + vy/H)]

    W and H denote the image width and height.

    To keep the example easy to understand, you can implement the transform with direct computation. Its time complexity is high, making it suitable for small images and teaching experiments rather than large ones.

    1. function dft2D(input, width, height, inverse = false) {
    2. const real = new Float64Array(width * height);
    3. const imag = new Float64Array(width * height);
    4. const sign = inverse ? 1 : -1;
    5. const scale = inverse ? 1 / (width * height) : 1;
    6. for (let v = 0; v < height; v++) {
    7. for (let u = 0; u < width; u++) {
    8. let sumReal = 0;
    9. let sumImag = 0;
    10. for (let y = 0; y < height; y++) {
    11. for (let x = 0; x < width; x++) {
    12. const angle = 2 * Math.PI *
    13. (u * x / width + v * y / height);
    14. const value = input[y * width + x];
    15. sumReal += value * Math.cos(angle);
    16. sumImag += sign * value * Math.sin(angle);
    17. }
    18. }
    19. const index = v * width + u;
    20. real[index] = sumReal * scale;
    21. imag[index] = sumImag * scale;
    22. }
    23. }
    24. return { real, imag };
    25. }

    In production, use the Fast Fourier Transform (FFT) instead, decomposing the 2D transform into row-wise and column-wise 1D transforms. This reduces the complexity from the high-order form of direct computation to a scale suitable for real applications.

    Magnitude and Phase Spectra

    The complex spectrum can be decomposed into magnitude and phase:

    1. Magnitude = sqrt(Re² + Im²)
    2. Phase = atan2(Im, Re)

    The corresponding code:

    1. function getMagnitudePhase(real, imag) {
    2. const magnitude = new Float64Array(real.length);
    3. const phase = new Float64Array(real.length);
    4. for (let i = 0; i < real.length; i++) {
    5. magnitude[i] = Math.hypot(real[i], imag[i]);
    6. phase[i] = Math.atan2(imag[i], real[i]);
    7. }
    8. return { magnitude, phase };
    9. }

    The Magnitude Spectrum

    The magnitude spectrum represents the strength of each frequency component. Because the value range varies widely, direct rendering leaves most of the image nearly black, so logarithmic compression is usually applied:

    1. function normalizeMagnitude(magnitude) {
    2. const output = new Float64Array(magnitude.length);
    3. let maxValue = 0;
    4. for (let i = 0; i < magnitude.length; i++) {
    5. output[i] = Math.log(1 + magnitude[i]);
    6. maxValue = Math.max(maxValue, output[i]);
    7. }
    8. if (maxValue === 0) return output;
    9. for (let i = 0; i < output.length; i++) {
    10. output[i] = output[i] / maxValue * 255;
    11. }
    12. return output;
    13. }

    When displaying the spectrum, the zero frequency is typically shifted to the image center. For coordinates (x, y), use a checkerboard-style swap:

    1. function shiftSpectrum(data, width, height) {
    2. const result = new Float64Array(data.length);
    3. for (let y = 0; y < height; y++) {
    4. for (let x = 0; x < width; x++) {
    5. const nx = (x + Math.floor(width / 2)) % width;
    6. const ny = (y + Math.floor(height / 2)) % height;
    7. result[ny * width + nx] = data[y * width + x];
    8. }
    9. }
    10. return result;
    11. }

    Drawing on the magnitude spectrum essentially modifies the energy of different frequency components. For example:

    • Drawing near the center may affect low-frequency structure;
    • Drawing in peripheral regions may affect edges and details;
    • Extensively covering high frequencies may blur the image;
    • Boosting frequencies in a specific direction may produce stripes or directional textures.

    The Phase Spectrum

    The phase spectrum’s value range is typically [-π, π]. To display it on a Canvas, map it linearly to [0, 255]:

    1. function phaseToDisplay(phase) {
    2. const output = new Float64Array(phase.length);
    3. for (let i = 0; i < phase.length; i++) {
    4. output[i] = (phase[i] + Math.PI) /
    5. (2 * Math.PI) * 255;
    6. }
    7. return output;
    8. }

    Phase is critical to an image’s spatial structure. Even with the magnitude spectrum unchanged, large-scale phase modifications can significantly alter object positions, edge organization, and contour relationships. Phase drawing therefore tends to cause more structural damage than magnitude drawing.

    Recovering the Complex Spectrum from Drawing Data

    What the user sees on the Canvas are grayscale display values, while the inverse transform requires the complex spectrum. The edited display result must therefore be converted back into magnitude or phase.

    Assuming magnitude and phase are ready, you can recombine them into real and imaginary parts:

    1. function composeComplex(magnitude, phase) {
    2. const real = new Float64Array(magnitude.length);
    3. const imag = new Float64Array(magnitude.length);
    4. for (let i = 0; i < magnitude.length; i++) {
    5. real[i] = magnitude[i] * Math.cos(phase[i]);
    6. imag[i] = magnitude[i] * Math.sin(phase[i]);
    7. }
    8. return { real, imag };
    9. }

    If only the magnitude spectrum is edited, keep the original phase; if only the phase spectrum is edited, keep the original magnitude. The three modes can be expressed uniformly:

    1. function rebuildSpectrum(original, editedMagnitude, editedPhase, mode) {
    2. const magnitude = editedMagnitude || original.magnitude;
    3. const phase = editedPhase || original.phase;
    4. if (mode === "magnitude") {
    5. return composeComplex(magnitude, original.phase);
    6. }
    7. if (mode === "phase") {
    8. return composeComplex(original.magnitude, phase);
    9. }
    10. if (mode === "both") {
    11. return composeComplex(magnitude, phase);
    12. }
    13. return {
    14. real: original.real.slice(),
    15. imag: original.imag.slice()
    16. };
    17. }

    The implementation must also handle conjugate symmetry. For real-valued images, the spectrum is conjugate symmetric. If the user edits one side without editing the mirrored position, the inverse transform may produce a noticeable imaginary part. Two common approaches:

    1. When modifying a point, simultaneously modify its conjugate-symmetric counterpart;
    2. After the inverse transform, take only the real part and apply reasonable clipping.

    The first approach is mathematically rigorous; the second is simpler to implement and well suited to interactive experiments.

    Canvas Drawing Interaction

    The drawing layer can simply be a second Canvas overlaid on the display Canvas. On mouse or touch events, convert screen coordinates to image coordinates:

    1. function getCanvasPoint(canvas, event) {
    2. const rect = canvas.getBoundingClientRect();
    3. const scaleX = canvas.width / rect.width;
    4. const scaleY = canvas.height / rect.height;
    5. return {
    6. x: (event.clientX - rect.left) * scaleX,
    7. y: (event.clientY - rect.top) * scaleY
    8. };
    9. }

    The drawing logic handles three stages: pointer down, move, and up:

    1. let drawing = false;
    2. let lastPoint = null;
    3. canvas.addEventListener("pointerdown", event => {
    4. drawing = true;
    5. lastPoint = getCanvasPoint(canvas, event);
    6. canvas.setPointerCapture(event.pointerId);
    7. });
    8. canvas.addEventListener("pointermove", event => {
    9. if (!drawing) return;
    10. const point = getCanvasPoint(canvas, event);
    11. const context = canvas.getContext("2d");
    12. context.strokeStyle = "#ffffff";
    13. context.lineWidth = 8;
    14. context.lineCap = "round";
    15. context.beginPath();
    16. context.moveTo(lastPoint.x, lastPoint.y);
    17. context.lineTo(point.x, point.y);
    18. context.stroke();
    19. lastPoint = point;
    20. });
    21. canvas.addEventListener("pointerup", () => {
    22. drawing = false;
    23. lastPoint = null;
    24. });

    It is recommended to keep the original spectrum display, drawing layer, and reconstruction result separate. This lets users clear drawings, recompute, and compare results before and after modification at any time.

    Horizontal Derivative and Image Reconstruction

    Beyond frequency-domain edits, you can also examine the image’s horizontal first-order derivative. For each row, the derivative is approximated as:

    1. d(x, y) = f(x + 1, y) - f(x, y)

    Implementation:

    1. function horizontalDerivative(image, width, height) {
    2. const derivative = new Float64Array(image.length);
    3. for (let y = 0; y < height; y++) {
    4. const row = y * width;
    5. for (let x = 0; x < width - 1; x++) {
    6. derivative[row + x] =
    7. image[row + x + 1] - image[row + x];
    8. }
    9. derivative[row + width - 1] = 0;
    10. }
    11. return derivative;
    12. }

    In theory, the original row can be recovered by accumulating the derivative:

    1. f(x, y) = f(0, y) + Σ d(k, y)

    But there is an important caveat: the derivative captures only change, not absolute brightness. Each row therefore requires an initial value. If that initial value is lost, the reconstruction may become globally brighter or darker, or drift entirely.

    1. function integrateDerivative(derivative, width, height, initialValue) {
    2. const output = new Float64Array(derivative.length);
    3. for (let y = 0; y < height; y++) {
    4. const row = y * width;
    5. output[row] = initialValue;
    6. for (let x = 1; x < width; x++) {
    7. output[row + x] =
    8. output[row + x - 1] + derivative[row + x - 1];
    9. }
    10. }
    11. return output;
    12. }

    If drawing modifies the derivative image, the reconstruction will show local brightness jumps, enhanced edges, or banding artifacts. Smoothing the derivative, limiting its amplitude, or using regularized reconstruction can reduce noise accumulation.

    Numeric Display and Result Clipping

    Inverse transform results rarely fall neatly within [0, 255]; they may be negative or exceed 255. Clip before display:

    1. function clampToByte(value) {
    2. return Math.max(0, Math.min(255, Math.round(value)));
    3. }
    4. function grayToImageData(gray, width, height) {
    5. const imageData = new ImageData(width, height);
    6. for (let i = 0; i < gray.length; i++) {
    7. const value = clampToByte(gray[i]);
    8. const p = i * 4;
    9. imageData.data[p] = value;
    10. imageData.data[p + 1] = value;
    11. imageData.data[p + 2] = value;
    12. imageData.data[p + 3] = 255;
    13. }
    14. return imageData;
    15. }

    A more robust approach is global normalization before display, but normalization changes overall brightness relationships, so it is worth offering both modes:

    • Fixed-range clipping: makes brightness changes easier to compare;
    • Automatic normalization: makes structural details easier to observe.

    The experiment page should clearly indicate which display mode is active, so users do not mistake display enhancement for new information produced by the algorithm itself.

    Performance and Engineering Tips

    Direct 2D DFT works fine for teaching and small images but slows down quickly as image size grows. Production implementations can be optimized in several ways:

    1. Use the FFT, decomposing the 2D computation into multiple 1D computations;
    2. Use Float32Array or Float64Array to reduce the overhead of ordinary arrays;
    3. Move computation into a background thread (Web Worker) to avoid blocking page interaction;
    4. Downscale images and preview at smaller sizes first;
    5. Run the inverse transform only after the user stops drawing, rather than on every pointer event;
    6. Cache the magnitude spectrum and update only modified regions;
    7. Decouple the drawing layer from the computation layer to reduce redundant rendering.

    The UI should also display the current image size, processing mode, whether auto-normalization is enabled, and the status of the most recent computation, helping users interpret the results correctly.

    Conclusion

    By moving between the spatial domain, frequency domain, magnitude spectrum, phase spectrum, and derivative domain, you can see directly that “image information” does not exist in a single form. Magnitude determines the energy distribution of frequency components, phase maintains the organization of spatial structure, derivatives highlight local change, and the inverse transform maps these abstract representations back into an observable image.

    Building this kind of experiment page with JavaScript and Canvas is valuable not only for learning digital image processing, but also as a foundation for front-end visualization, interactive algorithm demos, and image analysis tools. Future extensions could include 2D derivatives, edge detection, frequency-domain filtering, per-channel editing, undo/redo, and parameterized brushes — evolving the experiment from simple drawing into a full browser-based image transform platform.