gpt4 book ai didi

javascript - 使用 requestAnimationFrame() 绘制 Canvas 动画

转载 作者:行者123 更新时间:2023-11-28 03:32:54 24 4
gpt4 key购买 nike

我正处于开发游戏的第一步。我画了一个应该在 Canvas 中向右移动的卡农。这是我的代码:

            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);
});

Canvas 上什么也没有出现,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>

关于javascript - 使用 requestAnimationFrame() 绘制 Canvas 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58013914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com