The HTML <canvas>
aspect permits you to create interactive graphics on an online web page utilizing JavaScript. It supplies a drawing floor for JavaScript code to create dynamic animations, graphs, video games, and extra.
Syntax
The fundamental syntax for utilizing the <canvas>
aspect is:
1 |
<canvas id="canvas" width="1000" peak="1000"></canvas> |
The <canvas>
aspect might be given an id, and the width and peak of the canvas might be set with the corresponding attributes.
Examples
Right here’s an instance of a canvas aspect with a blue sq.. The HTML marks out the canvas, and the JavaScript paints the blue sq. on it:
1 |
<canvas id="canvas" width="400" peak="200"></canvas> |
2 |
|
3 |
<script>
|
4 |
let canvas = doc.querySelector("#canvas") |
5 |
let ctx = canvas.getContext("2nd") |
6 |
ctx.fillStyle ="blue" |
7 |
ctx.fillRect(10,10,50,50) |
8 |
</script>
|
The JavaScript variable, ctx
, represents the canvas context and units its fill coloration to blue
. Then, it attracts a rectangle on the canvas at place (10,10) with a width of fifty pixels and a peak of fifty pixels.
Consequence
Right here’s a extra superior instance which introduces movement and extra properties you may manipulate contained in the canvas aspect with JavaScript.
Consequence
On this instance, we create a ball that bounces across the canvas aspect. Right here’s what’s occurring:
- The
drawBall()
perform creates a radial gradient fromlightblue
tocornflowerblue
tomidnightblue
after which attracts the ball on the canvas. - The
updateBall()
perform updates the ball’s place and checks if it hits any of the partitions of the canvas. - The
gameLoop()
perform callsdrawBall()
andupdateBall()
on every iteration of the loop and clears the canvas every time. - Lastly, the
requestAnimationFrame()
perform is used to name thegameLoop()
perform repeatedly to create the animation.
Attributes
Listed here are a number of the widespread attributes used with the <canvas>
aspect:
-
id
: specifies a singular id for the aspect. -
width
: specifies the width of the canvas in pixels. -
peak
: specifies the peak of the canvas in pixels. - The
<canvas>
aspect additionally helps world attributes likeclass
,type
, andtitle
.
Content material
The <canvas>
aspect doesn’t help any content material, as all drawing is finished utilizing JavaScript.
Any textual content contained in the <canvas>
aspect might be displayed in browsers the place JavaScript is disabled.
Did You Know?
- The
<canvas>
aspect was launched in HTML5 as a substitute for utilizing plugins like Flash and Silverlight for creating dynamic graphics and animations. - The
<canvas>
aspect can be utilized to create varied graphs and charts, akin to bar charts, line charts, and pie charts. It can be used to create video games and animations utilizing JavaScript.