HTML5 Canvas
The <canvas> element creates an empty drawing area on the page. By itself it shows nothing. You draw on it with JavaScript, so it is used for charts, games and animations.
Create a canvas
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>
Always set width and height as attributes, and give the canvas an id so JavaScript can find it.
Draw on the canvas
We get the canvas, then ask for its 2d context, which has all the drawing methods.
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000;"></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// filled rectangle
ctx.fillStyle = "orange";
ctx.fillRect(20, 20, 150, 80);
// circle outline
ctx.beginPath();
ctx.arc(230, 60, 30, 0, 2 * Math.PI);
ctx.stroke();
// text
ctx.font = "20px Arial";
ctx.fillText("Hello Canvas", 20, 130);
</script>
This draws an orange rectangle on the left, a circle outline on the right, and the text “Hello Canvas” at the bottom of the canvas.
Common drawing methods
| Method | Use |
|---|---|
fillRect(x, y, w, h) | Filled rectangle |
strokeRect(x, y, w, h) | Rectangle outline |
beginPath(), moveTo(), lineTo(), stroke() | Draw a line |
arc(x, y, r, start, end) | Circle or arc |
fillText(text, x, y) | Write text |
clearRect(x, y, w, h) | Erase an area |
The point (0, 0) is the top left corner. The x value grows to the right and y grows downwards.
Note:
Canvas draws pixels, so it does not remember the shapes as elements. For sharp icons and logos that must scale, use SVG. Use canvas for games, charts with lots of data and image effects.
Summary
<canvas>is a drawing area controlled by JavaScript.- Get the context with
getContext("2d")and use methods likefillRect()andarc(). - You can learn JavaScript in our JavaScript Tutorial.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |