javascript - 带有 requestAnimationFrame() 的画布动画
问题描述
我正处于开发游戏的第一步。我画了一个应该在画布中移动的佳能。这是我的代码:
window.addEventListener('load', function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 185;
var y = 320;
var W = 30;
function drawCanon(x, y, W){
//CANON
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.moveTo(x, y);
ctx.beginPath();
ctx.lineTo(x + W/5 * 3, y);
ctx.lineTo(x + W/5 * 4, y + W * 2);
ctx.lineTo(x - W/5, y + W * 2);
ctx.lineTo(x, y);
ctx.closePath();
ctx.fill();
ctx.arc(x + W/10 * 3, y + 2 * W, W/2, 0, Math.PI);
ctx.fill();
//ROUES
ctx.fillStyle = "rgb(156, 92, 23)";
ctx.beginPath();
ctx.arc(x - W/50 * 12, y + W/50 * 102, W/5 * 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.arc(x + W/50 * 42, y + W/50 * 102, W/5 * 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
function draw(x, y, W){
drawCanon(x, y, W);
ctx.clearRect(0, 0, 400, 400);
x++;
window.requestAnimationFrame(function(){draw(x, y, W)}, 30);
}
draw(x, y, W);
});
画布上什么都没有出现,drawCanon() 和 clearRect 正常工作,但最后一行没有:window.requestAnimationFrame(function(){draw(x, y, W)});
有人可以帮助我吗?
解决方案
.requestAnimationFrame
唯一接受一个论点。此外,尽可能避免使用匿名函数,并且作为一个好的做法,限制函数中动画的 FPS(仅在经过一定时间后才执行)。
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 15;
var y = 10;
var W = 30;
var fps=1/60
const drawCannon = (x, y, W) => {
//CANON
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.moveTo(x, y);
ctx.beginPath();
ctx.lineTo(x + W/5 * 3, y);
ctx.lineTo(x + W/5 * 4, y + W * 2);
ctx.lineTo(x - W/5, y + W * 2);
ctx.lineTo(x, y);
ctx.closePath();
ctx.fill();
ctx.arc(x + W/10 * 3, y + 2 * W, W/2, 0, Math.PI);
ctx.fill();
//ROUES
ctx.fillStyle = "rgb(156, 92, 23)";
ctx.beginPath();
ctx.arc(x - W/50 * 12, y + W/50 * 102, W/5 * 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.arc(x + W/50 * 42, y + W/50 * 102, W/5 * 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
let then = 0
let animation = () => {
let now = new Date().getTime();
let elapsedTime = (now - then) / 1000
if ( elapsedTime > fps) {
ctx.clearRect(0, 0, 400, 400);
x++;
drawCannon(x, y, W)
then = new Date().getTime();
}
window.requestAnimationFrame(animation);
}
window.requestAnimationFrame(animation);
<canvas id="canvas"></canvas>
推荐阅读
- elasticsearch - Elasticsearch完成:每个文档有多个匹配项时的奇怪行为
- webpack - 使用 webpack 进行 vue 惰性转译
- mysql - 如何编写查询以找出我想要的结果
- extjs - 如何将数据加载到组合框中?
- iis - 向 web.config 添加新的处理程序
- apache-spark - Spark读取parquet压缩数据
- android - 如何使用文本跨度将 android textview 中的单词移动到下一个单词上方?
- docker - 更改容器运行时的日志级别
- python-3.x - 为什么 encode_base64 给我 TypeError: expected bytes-like object, not NoneType
- sql-server - 消息 7105,级别 22,删除查询中的状态 9