Command Palette

Search for a command to run...

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

Compositing and clipping

Each row is one setting. Reading pixels proves what each rule does.

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?

Compositing and clipping

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

source-over: overlap: 231,111,81,255 | only new: 231,111,81,255 | only old: 42,157,143,255
globalAlpha 0.5: overlap: 137,134,112,255 | only new: 231,112,82,128 | only old: 42,157,143,255
destination-out: overlap: 0,0,0,0 | only new: 0,0,0,0 | only old: 42,157,143,255
multiply: overlap: 38,69,46,255 | only new: 231,111,81,255 | only old: 42,157,143,255
lighter: overlap: 255,255,224,255 | only new: 231,111,81,255 | only old: 42,157,143,255
destination-over: overlap: 42,157,143,255 | only new: 231,111,81,255 | only old: 42,157,143,255
clip: inside the circle 38,70,83,255 | same bar, outside the circle 0,0,0,0
after restore, drawing is not clipped: 233,196,106,255