首页 > 解决方案 > 如何使用 requestAnimationFrame 在画布中为图像设置动画?

问题描述

我想在 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();

通常图像正在加载,但是当我尝试在其中添加动画帧时,图像就会消失。

标签: javascriptcsshtml5-canvasrequestanimationframe

解决方案


您只需要加载一次图像。

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>


推荐阅读