javascript - 如何使用 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();
通常图像正在加载,但是当我尝试在其中添加动画帧时,图像就会消失。
解决方案
您只需要加载一次图像。
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>
推荐阅读
- python - 有没有办法在 Python 的 next 函数中包含多个条件?
- c# - 在将 PDF 页面转换为图像时裁剪 Pdf 页面
- spring-boot - 如果方法被另一个带注释的方法调用,则检查 Spring AOP
- reactjs - 我收到此错误:无法对未安装的组件执行 React 状态更新。但我不知道该怎么办
- java - 如何从 Firebase 存储下载音频文件并将它们(文件)保存到外部存储中的文件夹
- swift - 单个对象可能有多种类型 - 解码
- c# - 单声道游戏中的全屏分辨率问题
- python - 使用 QML 到 python 设置连接和信号目标
- java - 我的应用程序在删除后会记住登录密码并重新安装
- flutter - Flutter,从不渲染调用的父小部件中设置 state()