我想使用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();
通常图像正在加载,但是当我尝试在其中添加动画帧时,图像消失了。
答案 0 :(得分:1)
您只需加载一次图像。
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>