- Home
- /
- Tutorials
- /
- HTML Tutorial
- /
- HTML <canvas> Tag
HTML Tags
HTML <canvas> Tag
The canvas tag is a blank drawing surface. HTML only creates the empty rectangle; everything on it, shapes, charts, game graphics, is drawn by JavaScript, pixel by pixel. It is how browser games and many charting libraries work.
Syntax
html
<canvas id="canvasID" width="value" height="value">
Fallback content if canvas is not supported.
</canvas>| Attribute | What it does |
|---|---|
| width | The drawing width in pixels. Default 300. |
| height | The drawing height in pixels. Default 150. |
Set the size with these attributes, not only with CSS. CSS stretches the finished picture, so a canvas that is 300 pixels wide inside but shown 600 pixels wide looks blurry and distorted.
Example
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Tag Example</title>
<style>
canvas { border: 2px solid #29AB87; }
</style>
</head>
<body>
<h2>Drawing on Canvas</h2>
<canvas id="myCanvas" width="400" height="200">
Your browser does not support the HTML canvas tag.
</canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw a rectangle
ctx.fillStyle = "#FF0000";
ctx.fillRect(50, 50, 150, 100);
// Draw a circle
ctx.beginPath();
ctx.arc(300, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = "#0000FF";
ctx.fill();
</script>
</body>
</html>A red rectangle and a blue circle appear inside a green border. The script gets the canvas's 2D drawing context with getContext("2d"), sets a fill color, and draws: fillRect for the rectangle, arc and fill for the circle.
How drawing works
ctx.fillStyleandctx.strokeStyleset the fill and line colors.fillRect(x, y, width, height)draws a filled rectangle, measured from the top-left corner.- For other shapes, start with
beginPath(), describe the path withmoveTo,lineToorarc, then callfill()orstroke(). fillText("Hello", x, y)draws text.
Once drawn, shapes are just pixels. To move something, you clear the canvas and draw everything again, many times a second for an animation.
Browser Support
Chrome | Edge | Firefox | Safari | Opera | IE9+ |
|---|---|---|---|---|---|
| Yes | Yes | Yes | Yes | Yes | Yes |
Good to know
- Screen readers cannot see what is drawn. Put a text description inside
<canvas>, or next to it, for anything that carries information, like a chart's data. - For icons, logos and simple diagrams, SVG is often better: it stays sharp at any size and its parts can be styled and clicked.
- On high-resolution screens, draw at twice the size and scale the canvas down with CSS for sharp results.
HTML <canvas> Tag exercises
Add a canvas
Add a canvas with the id board that is 300 wide and 150 high.
Result
