Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.5 — Images, Pixels and Compositing
Data Visualization · Example 1 of 2

drawImage, getImageData and putImageData

Edge cases: an image that has not loaded, a read outside the canvas, and a read of width 0.

A canvas can draw images, read and write its own pixels, mix new paint with old in many ways, and clip drawing to a shape. Reading pixels of an image from another site is blocked, and the error is the one to know.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 4 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write grey(ctx, x, y, w, h) that turns an area to greyscale with getImageData and putImageData (use the average of red, green and blue).

02

Paint a wide teal rectangle that only shows inside a circle of radius 30, using clip, and make sure later drawing is not clipped.

Explain it without notes

01

Why does drawImage sometimes paint nothing and show no error?

02

What is in ImageData.data and how long is it for a 10 × 5 area?

03

What makes a canvas tainted, what stops working, and how do you avoid it?

drawImage, getImageData and putImageData

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

drawImage before the image loaded: no error, pixel alpha 0
middle of the stretched crop: 233,196,106,255
pixels: 1600 numbers: 6400
inverted corner: 213,98,112,255
outside the canvas: 0,0,0,0
IndexSizeError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The source width is 0.