DEV Community

Cover image for Understanding HTML canvas
Nelson chege
Nelson chege

Posted on

Understanding HTML canvas

HTML canvas is a graphic interface that can be used to create video games and animation using JavaScript and the canvas element in HTML.it is also a lightweight solution when you want to create animations without any additional frameworks and libraries.

How to setup a basic playground

you only need JavaScript and an html file to getting started using Canvas.

in the HTML file ,add the canvas element and a script tag to your JavaScript file

inside the JavaScript file, First select the canvas element in the HTML, using any of the document methods.you can get the canvas depending on how you have initialized the canvas element in you HTML file.

const canvas  = document.querySelector('canvas')
Enter fullscreen mode Exit fullscreen mode

then create the main object that will be used in whatever you want to make of it. here is a link to the different context that are available when using Canvas.

const ctx = canvas.getContext('2d')
Enter fullscreen mode Exit fullscreen mode

How to draw something on canvas

the object created ctx contains different methods that are used to create the different things within the canvas context

for drawing rectangles , you can use the .fillRect() method

ctx.fillRect(0,0,50,150)
%%the first two argument are for the postions of the rectangle being drawn, and the other  one is for the height and with of the said rectangle  %%
Enter fullscreen mode Exit fullscreen mode

you can also use the .fillStyle() method to add colour to it

How to create a basic animation

a callback function can be created to tell the browser that you wish to perform an animation.

function animate(){
 window.requestAnimationFrame(animate)
}

animate()
Enter fullscreen mode Exit fullscreen mode

in this case, it will be an infinite callback function that will continue running the function.This will make the screen refresh each time the function run.
This is helpful because in things like animation, the screen needs to change for each frame in the animation.

Creating an object that moves

for a simple example of creating a small game that you can move a character around,ill be creating an object that can move side to side and jump.

First setup the object and give it full height and width of the screen

const canvas = document.querySelector('canvas')
const ctx = canvas.getCOntext('2d')

canvas.witdth = window.innerWitdth;
canvas.height = window.innerHeight;
Enter fullscreen mode Exit fullscreen mode

Next ,create a class that will hold the properties that we want object to contain (lets can it a player).

class Player{
  constructor({position.velocity}){
    this.position = position
    this.velocity = velocity
    this.height = 150 pixels
  }
  draw(){
    canvas.fillStyle ='red'
    canvas.fillRect(this.position.x,this.position.y,50,this.height)
 }
 update(){
    this.draw();
    this.position.x += this.velocity.x
    this.position.y += this.velocity.y

  if(this.position.y + this.height + this.velocity.y >= canvas.height){
  this.velocity.y = 0
  }else{
    this.velocity.y += 0.2
  }
 }
}
Enter fullscreen mode Exit fullscreen mode

now time to create a player instance from the class created

const Player1 = new PLayer({postion:{x:0,y:0},velocity:{x:0,y:5}})
Enter fullscreen mode Exit fullscreen mode

Next thing is to write functions that takes in input from the keys pressed on the keyboard, and also adding helper variables

const Keys = {
    a:{ pressed:false },
    d:{ prassed:false }
    w:{ passed:false }
}

window.addEventLIstener("keyDown",(event)=>{
 switch (event.key){
   case "d":
     Keys.d.pressed = true;
     break;
   case "a":
     Keys.a.pressed = true;
     break;
  %%  this will handle the player jumping  %%   
   case "w":
     player1.velocity.y = -10;
     break;
 }
})

window.addEventLIstener("keyUp",()=>{
  case "d":
     Keys.d.pressed = false;
     break;
   case "a":
     Keys.a.pressed = false;
     break;
})
Enter fullscreen mode Exit fullscreen mode

finally , create a callback function that would be used to re render "yeah I'm used to that term from the react world ;)" and handle the animation

function animate(){
   windows.requestAnimationFrame(animate)
   ctx.fillStyle ='black';
   ctx.fillRect(0,0 canvas.width,canvas.height);
   player1.update()

   player1.velocity.x = 0

  if (keys.a.pressed && player.lastKeyPressed === "a") {
       player.velocity.x = -10;
  else if (keys.d.pressed && player.lastKeyPressed === "d") {
       player.velocity.x = 10;
  }
}

animate()
Enter fullscreen mode Exit fullscreen mode

conclusion

HTML canvas is a great way to getting started if interested in making animation using javascript. It's Lightweight from it being a native HTML element and no extra libraries or framework needed

Top comments (0)