Skip to content Skip to sidebar Skip to footer

How To Add Event Listener And Move An Object In Canvas Using ES6 Classes?

I'm creating a small game where you can move a star/ufo. I'm having a hard time to figure out how I should make it move. With functional programming its easy, but how do we go abou

Solution 1:

Please take a look at this code (a little bit different of what you had in mind)

let keys = {ArrowUp:false,ArrowDown:false,ArrowLeft:false,ArrowRight:false};

         window.addEventListener('keydown', function(e){
            keys[e.code] = true;
         });

         window.addEventListener('keyup', function(e){
            keys[e.code] = false;
         });

  /*UFO*/
   class Ufo {
      constructor(x, y) {
         this.x = x,
         this.y = y,
         this.velocity = {
            x: 3,
            y: 3
         }
      }
      
      draw(c) {
         c.save()
         c.beginPath()
         c.arc(this.x, this.y, 50, 0, Math.PI * 2, false)
         c.fillStyle = "#fff";
         c.shadowColor = "#e3eaef";
         c.shadowBlur = 20;
         c.fill()
         c.closePath()
         c.restore()
      }
      
      update(c) {
        if(keys.ArrowUp){this.y -= this.velocity.y;}
        if(keys.ArrowDown){this.y += this.velocity.y;}
        if(keys.ArrowLeft){this.x -= this.velocity.x;}
        if(keys.ArrowRight){this.x += this.velocity.x;}
        this.draw(c);
      }
   }

   /* Canvas*/		
   class CanvasDisplay {
      constructor() {
         this.canvas = document.querySelector('canvas');
		     this.ctx = this.canvas.getContext('2d');       
         this.cw = this.canvas.width = window.innerWidth;
         this.ch = this.canvas.height = window.innerHeight;
         
         this.ufo = new Ufo(this.cw / 2, this.ch / 2);
       
         this.ctx.fillStyle = this.grd();
      }
      
      grd(){
         let grd = this.ctx.createLinearGradient(0, 0, 0, this.ch);
         grd.addColorStop(0, '#171e26');
         grd.addColorStop(1, '#3f586b');
         return grd;
      }
      
       animate() {
         window.requestAnimationFrame(this.animate.bind(this));
         this.ctx.fillRect(0,0,this.cw,this.ch);
         this.ufo.update(this.ctx);
      }
   }

   let canv= new CanvasDisplay();

   canv.animate();
body {
  overflow: hidden;
}
canvas {
  display: block;
}
<canvas></canvas>

lease take a look at this code:


Post a Comment for "How To Add Event Listener And Move An Object In Canvas Using ES6 Classes?"