Friday, December 1, 2023
HomeVideo EditingHTML Factor: canvas | Envato Tuts+

HTML Factor: canvas | Envato Tuts+

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.


The fundamental syntax for utilizing the <canvas> aspect is:

<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.


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:

<canvas id="canvas" width="400" peak="200"></canvas>

  let canvas = doc.querySelector("#canvas")
  let ctx = canvas.getContext("2nd")
  ctx.fillStyle ="blue"

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.


Right here’s a extra superior instance which introduces movement and extra properties you may manipulate contained in the canvas aspect with JavaScript.


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 from lightblue to cornflowerblue to midnightblue 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 calls drawBall() and updateBall() on every iteration of the loop and clears the canvas every time.
  • Lastly, the requestAnimationFrame() perform is used to name the gameLoop() perform repeatedly to create the animation.


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 like class, type, and title.

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.

Be taught Extra



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments