Graphics & In-Browser ProcessingUpdated: 2026-11-06

HTML5 Canvas 2D Context, Image Manipulation & Pixel Math Reference

Quick lookup for drawImage scaling, getImageData pixel manipulation, gradients, clipping masks, and export toBlob.

The HTML5 `<canvas>` element and its 2D Rendering Context provide low-level bitmap manipulation capabilities directly inside web browsers. DocSwift uses the Canvas API to crop, resize, rotate, compress, and strip EXIF metadata from photographs locally in browser memory without sending a single byte to external servers.

Context Initialization & Transformations

Setting up high-DPI canvases and coordinate matrices.

Method / PropertyParametersPurpose
`canvas.getContext("2d")``{ willReadFrequently: true }`Optimizes canvas memory for fast getImageData reads
`ctx.scale(x, y)``dpr, dpr`Scales canvas coordinate grid for Retina / 4K displays
`ctx.rotate(angle)``radians (deg * Math.PI / 180)`Rotates canvas around current origin
`ctx.save()` / `ctx.restore()`NonePushes and pops drawing state (transforms, styles, clips)

Image Drawing & Crop Math

The 3 signatures of ctx.drawImage for drawing, scaling, and slicing.

drawImage SignatureArgumentsUse Case
Basic (1:1)`ctx.drawImage(img, dx, dy)`Draw image at native resolution
Scaled Resize`ctx.drawImage(img, dx, dy, dWidth, dHeight)`Scale or resize image to target canvas dimensions
Slice & Crop`ctx.drawImage(img, sx, sy, sW, sH, dx, dy, dW, dH)`Crop source rectangle and draw into destination canvas

Direct Pixel Manipulation (ImageData)

Accessing raw Uint8ClampedArray RGBA pixel buffers.

StepCode SnippetDescription
1. Read Pixels`const imgData = ctx.getImageData(0, 0, w, h);`Reads 32-bit RGBA pixel array
2. Pixel Loop`const d = imgData.data; for (let i=0; i<d.length; i+=4) ...``d[i]`=Red, `d[i+1]`=Green, `d[i+2]`=Blue, `d[i+3]`=Alpha
3. Write Back`ctx.putImageData(imgData, 0, 0);`Paints modified pixels back onto canvas
4. Export Blob`canvas.toBlob(blob => {}, "image/webp", 0.85);`Compresses canvas into downloadable WebP/JPEG Blob

Frequently Asked Questions

How do I prevent blurry images on high-DPI (Retina) screens with Canvas?

Multiply `canvas.width` and `canvas.height` by `window.devicePixelRatio`, while keeping `canvas.style.width` and `canvas.style.height` at standard CSS pixel dimensions, then call `ctx.scale(dpr, dpr)`.

Why should I pass { willReadFrequently: true } to getContext?

It informs the browser to keep the canvas in CPU system RAM rather than GPU VRAM, speeding up repeated `getImageData` pixel operations by up to 10x.