Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Canvas 2D: clearing, drawing, and editing pixels

Distinguish Canvas 2D drawing operations from direct bitmap reads and writes, and know when each coordinate system applies.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const ctx = canvas.getContext('2d');

ctx.clearRect(x, y, width, height);

ctx.drawImage(image, dx, dy);
ctx.drawImage(image, dx, dy, dw, dh);
ctx.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);

const snapshot = ctx.getImageData(sx, sy, sw, sh);
const configuredSnapshot = ctx.getImageData(sx, sy, sw, sh, settings);

ctx.putImageData(imageData, dx, dy);
ctx.putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight);

CanvasRenderingContext2D.clearRect/drawImage/getImageData/putImageData groups four instance methods on the context returned by canvas.getContext('2d'). They are Web APIs, not ECMAScript 2024 features. clearRect() respects the current transform and clip. It clears to transparent black (opaque black with alpha: false) without resetting drawing state or the current path. Call beginPath() when you want to start a new path.

drawImage() takes a ready CanvasImageSource, such as an image or another canvas, not ImageData. The 3-argument form draws the whole source at its intrinsic size; the 5-argument form sets the destination size; the 9-argument form maps a source rectangle to a destination rectangle. Negative dimensions extend a rectangle in the opposite direction without flipping the image. Drawing respects the transform, clip, and compositing state. If an image is still loading and not yet usable, drawImage() does not draw it. A fully available, decodable image can be drawn without a prior decode() call or a predecoded frame. A source canvas with a zero dimension throws InvalidStateError.

getImageData() reads bitmap pixels independently of the transform and clip. It returns a separate ImageData snapshot: editing data does not change the canvas. The array stores RGBA values row by row; the first channel of snapshot pixel (x, y) is at (y * imageData.width + x) * 4. Out-of-bounds pixels read as transparent black. Negative sw or sh extend the rectangle in the opposite direction; a zero dimension throws IndexSizeError.

putImageData() replaces pixels without scaling, transformation, context clipping, or blending. The 7-argument form selects a dirty rectangle inside ImageData, not on the destination: pixel (x, y) goes to (dx + x, dy + y). A detached buffer throws InvalidStateError. Color-space conversion and alpha premultiplication can change read-back values, especially for translucent pixels.

Drawing a cross-origin resource without CORS approval can make the bitmap no longer origin-clean. Reads then throw SecurityError, even after clearRect(). For cross-origin resources, use a CORS request and appropriate server permission. The default rgba-unorm8 readback format uses Uint8ClampedArray; check your target browsers before relying on options such as display-p3 or rgba-float16 (Float16Array).

Examples

<!doctype html>
<meta charset="utf-8">
<title>Canvas 2D pixel readback</title>
<canvas id="source" width="2" height="1" hidden></canvas>
<canvas id="destination" width="2" height="1" hidden></canvas>
<script>
  const source = document.getElementById('source');
  const canvas = document.getElementById('destination');
  const src = source.getContext('2d');
  const ctx = canvas.getContext('2d');
  src.fillStyle = '#ff0000';
  src.fillRect(0, 0, 2, 1);
  ctx.drawImage(source, 0, 0);
  ctx.clearRect(0, 0, 1, 1);

  const snapshot = ctx.getImageData(0, 0, 2, 1);
  console.log(snapshot.data.join(','));
  snapshot.data.set([0, 0, 255, 255], 4);
  ctx.putImageData(snapshot, -1, 0, 1, 0, 1, 1);
  console.log(ctx.getImageData(0, 0, 2, 1).data.join(','));
</script>

Result

0,0,0,0,255,0,0,255
0,0,255,255,255,0,0,255

The first line shows the cleared left pixel and the red right pixel. The code changes the snapshot’s right pixel to blue, then writes only that pixel with `dx = -1`. The second line shows blue on the left and unchanged red on the right.

Related lessons

  • JavaScript · Lesson 33 · Advanced · Version: 4

Sources