我想在 HTML5 canvas 中使用 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();
通常图像正在加载,但当我尝试在其中添加动画帧时图像消失了。
最佳答案
您只需要加载一次图像。
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>
关于javascript - 如何使用 requestAnimationFrame 为 Canvas 中的图像设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52438094/