HTML5 Canvas 2D Context, Image Manipulation & Pixel Math Reference
Quick lookup for drawImage scaling, getImageData pixel manipulation, gradients, clipping masks, and export toBlob.
Table of Contents
Context Initialization & Transformations
Setting up high-DPI canvases and coordinate matrices.
| Method / Property | Parameters | Purpose |
|---|---|---|
| `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()` | None | Pushes and pops drawing state (transforms, styles, clips) |
Image Drawing & Crop Math
The 3 signatures of ctx.drawImage for drawing, scaling, and slicing.
| drawImage Signature | Arguments | Use 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.
| Step | Code Snippet | Description |
|---|---|---|
| 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 |
Interactive Client-Side Tools for this Guide
Test and run these patterns directly inside your browser with zero server uploads:
Image Resizer (Passport & Custom Dimensions)
Quickly resize photos for passport applications, visa forms, resume uploads, or social media with aspect ratio lock.
Image Compressor (JPG, PNG & WebP)
Reduce photo file size for web publishing, email attachments, and online forms with instant live preview.
Base64 to Image Decoder & File Downloader
Convert raw Base64 strings and data:image URIs back into crisp PNG, JPEG, or WEBP files with instant visual preview and dimension inspection.
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.