简体   繁体   English

如何使用requestAnimationFrame对画布中的图像进行动画处理?

[英]How to animate an image in canvas using requestAnimationFrame?

I want to move an image from left to right using requestAnimationFrame in HTML5 canvas. 我想使用HTML5画布中的requestAnimationFrame从左向右移动图像。

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. 通常,图像正在加载,但是当我尝试在其中添加动画帧时,图像消失了。

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM