Category: Canvas
Changes the active canvas to the canvas with the specified id (other canvas commands only affect the active canvas).
Drawing apps can use multiple, overlaid canvases, each with their own changeable pen color and pen width. Only one canvas can be drawn on at a time, the active canvas. The first canvas to be created is automatically activated. All canvas drawing commands (such as line() and rect) draw on the active canvas. Likewise, all canvas state commands (such as setFillColor and setStrokeColor) change the state of the active canvas only.
Drawing on a canvas differs from a turtle drawing in that the actual pixels are accessible to the programmer in a three dimensional array.
// Two overlapping canvases. Changing the stroke width and color did not affect canvas2. createCanvas("canvas1"); createCanvas("canvas2"); setStrokeWidth(10); setStrokeColor("blue"); setFillColor("yellow"); circle(160, 240, 50); setActiveCanvas("canvas2"); rect(90, 170, 140, 140);
Example: Smiley Face Draw a smiley face. The second canvas is smaller and placed where the mouth should go. Since drawing only occurs within the bounds of a canvas, the circle drawn on the second canvas is cut off, or clipped, so that only the portion inside the canvas is visible.
// Draw a smiley face. The second canvas is smaller and placed where the mouth should go. Since drawing only occurs within the bounds of a canvas, the circle drawn on the second canvas is cut off, or clipped, so that only the portion inside the canvas is visible. createCanvas("face"); setFillColor("yellow"); circle(160, 240, 100); setFillColor("black"); circle(125, 215, 20); circle(195, 215, 20); createCanvas("mouth", 120, 50); setActiveCanvas("mouth"); setPosition("mouth", 100, 260); setStrokeWidth(15); circle(60, -15, 50);
Example: Front to Back Draw on three canvases, the later created canvases overlay the earlier ones. The order of the drawing is irrelevant.
// Draw on three canvases, the later created canvases overlay the earlier ones. The order of the drawing is irrelevant. createCanvas("back"); createCanvas("middle"); createCanvas("front"); setActiveCanvas("front"); setStrokeWidth(30); setStrokeColor("blue"); line(60, 30, 60, 230); line(30, 60, 230, 60); setActiveCanvas("middle"); setStrokeWidth(30); setStrokeColor("red"); line(130, 30, 130, 230); line(30, 130, 230, 130); setActiveCanvas("back"); setStrokeWidth(30); setStrokeColor("green"); line(200, 30, 200, 230); line(30, 200, 230, 200);
setActiveCanvas(id);
Name | Type | Required? | Description |
---|---|---|---|
id | string | Yes | The unique identifier for the canvas to activate. Must begin with a letter, contain no spaces, and may contain letters, digits, - and _. |
No return value. No visible effect of its own. It only changes the canvas that will be affected by subsequent canvas commands.
Found a bug in the documentation? Let us know at documentation@code.org
Found a bug in the documentation? Let us know at documentation@code.org