Shivam Chhetri
Shivam Chhetri

Reputation: 697

How to animate an image in canvas using requestAnimationFrame?

I want to move an image from left to right using requestAnimationFrame in HTML5 canvas.

let canvas= document.querySelector("canvas");
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
let c= canvas.getContext('2d');

let image= new Image();
image.src="./balloon.png";

let x=0;

function draw(){
    image.addEventListener("load",()=>{
        c.drawImage(image,x,0);
    });  
}

function update(){
    x+=1;
    draw();
}

function animate(){
    c.clearRect(0,0,canvas.width,canvas.height);
    requestAnimationFrame(animate);
    update();  
}
animate();

Normally image is loading but as I try to add animation frame in it then the image disappears.

Upvotes: 1

Views: 2957

Answers (1)

enxaneta
enxaneta

Reputation: 33062

You need to load the image only once.

let canvas= document.querySelector("canvas");
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
let c= canvas.getContext('2d');

let image= new Image();
image.src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/darwin300.jpg";

let x=0;

 image.addEventListener("load",()=>{
        c.drawImage(image,x,0);
    });  

function draw(){
 
        c.drawImage(image,x,0);
  
}

function update(){
    x+=1;
    draw();
}


function animate(){
    c.clearRect(0,0,canvas.width,canvas.height);
    requestAnimationFrame(animate);
    update();  
}
animate();
<canvas></canvas>

Upvotes: 3

Related Questions