HTML Canvas
Write the commands to draw a filled circle with a radius of 20.
Understand the topic
The 2D canvas context has methods for rectangles, paths, text, transforms, and images. Drawing changes the bitmap, not a retained collection of HTML shapes. Save and restore isolate drawing state such as fill color or transforms. Clear the appropriate rectangle before redrawing dynamic content. Provide equivalent text for meaningful charts and diagrams.
Worked example
<table><caption>Common Canvas 2D operations</caption><tr><th scope="col">Operation</th><th scope="col">Purpose</th></tr><tr><td>fillRect(x, y, w, h)</td><td>Fill a rectangle</td></tr><tr><td>clearRect(x, y, w, h)</td><td>Clear pixels</td></tr><tr><td>beginPath(), moveTo(), lineTo(), stroke()</td><td>Build and draw a path</td></tr><tr><td>arc(x, y, r, start, end)</td><td>Add a circular arc</td></tr><tr><td>fillText(text, x, y)</td><td>Draw text</td></tr><tr><td>save(), restore()</td><td>Preserve drawing state</td></tr></table>
Angles for arc use radians. A full circle extends from zero to 2 * Math.PI.
Practice
Write the commands to draw a filled circle with a radius of 20.
Show a suggested answer
ctx.beginPath();
ctx.arc(50, 50, 20, 0, 2 * Math.PI);
ctx.fill();Common mistake
Do not assume drawing text on a canvas creates a selectable or semantic text node.