The HTML <canvas>
element allows you to create interactive graphics on a web page using JavaScript. It provides a drawing surface for JavaScript code to create dynamic animations, graphs, games, and more.
Syntax
The basic syntax for using the <canvas>
element is:
1 | <canvas id="canvas" width="1000" height="1000"></canvas> |
The <canvas>
element can be given an id, and the width and height of the canvas can be set with the corresponding attributes.
Examples
Here’s an example of a canvas element with a blue square. The HTML marks out the canvas, and the JavaScript paints the blue square on it:
1 | <canvas id="canvas" width="400" height="200"></canvas> |
2 | |
3 | <script>
|
4 | let canvas = document.querySelector("#canvas") |
5 | let ctx = canvas.getContext("2d") |
6 | ctx.fillStyle ="blue" |
7 | ctx.fillRect(10,10,50,50) |
8 | </script>
|
The JavaScript variable, ctx
, represents the canvas context and sets its fill color to blue
. Then, it draws a rectangle on the canvas at position (10,10) with a width of 50 pixels and a height of 50 pixels.
Result
Here’s a more advanced example which introduces motion and additional properties you can manipulate inside the canvas element with JavaScript.
Result
In this example, we create a ball that bounces around the canvas element. Here’s what’s going on:
- The
drawBall()
function creates a radial gradient fromlightblue
tocornflowerblue
tomidnightblue
and then draws the ball on the canvas. - The
updateBall()
function updates the ball’s position and checks if it hits any of the walls of the canvas. - The
gameLoop()
function callsdrawBall()
andupdateBall()
on each iteration of the loop and clears the canvas each time. - Finally, the
requestAnimationFrame()
function is used to call thegameLoop()
function repeatedly to create the animation.
Attributes
Here are some of the common attributes used with the <canvas>
element:
-
id
: specifies a unique id for the element. -
width
: specifies the width of the canvas in pixels. -
height
: specifies the height of the canvas in pixels. - The
<canvas>
element also supports global attributes likeclass
,style
, andtitle
.
Content
The <canvas>
element does not support any content, as all drawing is done using JavaScript.
Any text inside the <canvas>
element will be displayed in browsers where JavaScript is disabled.
Did You Know?
- The
<canvas>
element was introduced in HTML5 as an alternative to using plugins like Flash and Silverlight for creating dynamic graphics and animations. - The
<canvas>
element can be used to create various graphs and charts, such as bar charts, line charts, and pie charts. It can also be used to create games and animations using JavaScript.