The basic syntax for using the
<canvas> element is:
<canvas id="canvas" width="1000" height="1000"></canvas>
<canvas> element can be given an id, and the width and height of the canvas can be set with the corresponding attributes.
<canvas id="canvas" width="400" height="200"></canvas>
let canvas = document.querySelector("#canvas")
let ctx = canvas.getContext("2d")
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.
In this example, we create a ball that bounces around the canvas element. Here’s what’s going on:
drawBall()function creates a radial gradient from
midnightblueand then draws the ball on the canvas.
updateBall()function updates the ball’s position and checks if it hits any of the walls of the canvas.
updateBall()on each iteration of the loop and clears the canvas each time.
- Finally, the
requestAnimationFrame()function is used to call the
gameLoop()function repeatedly to create the animation.
Here are some of the common attributes used with the
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.
<canvas>element also supports global attributes like
Any text inside the
Did You Know?
<canvas>element was introduced in HTML5 as an alternative to using plugins like Flash and Silverlight for creating dynamic graphics and animations.