You might see <canvas> Element reference while reading someone else’s HTML, or need it while building a page of your own. Instead of memorizing a definition, look at a working example and see when the element makes sense.
The Idea in Plain English
Provides a bitmap drawing surface controlled with JavaScript. Include fallback text or an accessible alternative for meaningful graphics.
For a reference page, pay attention to where the element is allowed, whether it needs a closing tag, and what other elements it can contain.
A Working Example
Read the sample once before copying it. Notice the element names and attribute values, then compare them with the explanation below.
<canvas id="drawing" width="240" height="100">
A rectangle will appear here.
</canvas>
<script>
const drawing = document.querySelector("#drawing");
const context = drawing.getContext("2d");
context.fillRect(30, 20, 120, 50);
</script>
What Each Part Does
- The canvas provides a pixel drawing surface; JavaScript draws into it.
- The script element can load code or hold data; the type attribute tells the browser how to treat its contents.
- id names an element for labels, fragments, CSS or JavaScript; IDs should be unique.
- width reserves the image or embedded resource’s intended horizontal dimension.
- height reserves the image or embedded resource’s intended vertical dimension.
A filled rectangle is drawn when canvas is supported and JavaScript runs.
Try It Yourself
Try replacing the example content with your own while keeping the valid HTML structure.
Common Beginner Mistakes
- Using canvas for essential information without providing a text equivalent.
- Changing several parts of the example at once, making it difficult to see which part caused a different result.
- Choosing a tag only because its default appearance looks right, without checking whether it describes the content correctly.
Key Takeaways
- Provides a bitmap drawing surface controlled with JavaScript. Include fallback text or an accessible alternative for meaningful graphics.
- A filled rectangle is drawn when canvas is supported and JavaScript runs.
- Test the markup in a browser, and check accessibility and real-world behavior where relevant.