形状在 HTML5 canvas 上移动,但它们不应该:requestAnimationFrame()

Shapes moving on an HTML5 canvas when they're not supposed to: requestAnimationFrame()

我想创建许多矩形,这些矩形从 html-canvas 的顶部开始并开始向下移动,直到它们从 canvas 的视图框中消失。所以我创建了一个带有很多参数(x 位置、y 位置、宽度、高度、颜色、上下文)的 class,这样我就可以使用 for 循环来创建许多带有我想要的任何参数的矩形对象传递给他们。问题是... 鼓声

一旦我将创建矩形对象并将它们设置为动画的函数传递给 requestAnimationFrame 方法,形状就开始向下移动。哎呀,我什至没有告诉他们搬家!

够了,这里是代码:(全屏查看代码片段)

function resize(canvasElement) {
    window.addEventListener("resize", function () {
        canvasElement.width = window.innerWidth / 3;
        canvasElement.height = window.innerHeight * 0.9975;
    })
}
var radius = 5;
class roundRect {
    constructor(rectX, rectY, rectHeight, rectWidth, stroke, fill, c) {
        c.clearRect(0, 0, 1000, 1000);
        c.beginPath();
        c.strokeStyle = stroke;
        c.fillStyle = fill;
        c.moveTo(rectX + rectWidth/2, rectY);
        c.arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + rectHeight, radius);
        c.arcTo(rectX + rectWidth, rectY + rectHeight, rectX, rectY + rectHeight, radius);
        c.arcTo(rectX, rectY + rectHeight, rectX, rectY, radius);
        c.arcTo(rectX, rectY, rectX + rectWidth / 2, rectY, radius);
        c.closePath();
        c.fill();
        c.stroke();
    }
}
function animate(rectYpar) {
    new roundRect(50, rectYpar, 100, 8, "red", "red", ctx);
    requestAnimationFrame(animate);
}
{
    var canvas = document.body.querySelector("#canvasOne");
    canvas.width = window.innerWidth / 3;
    canvas.height = window.innerHeight * 0.9975;
    resize(canvas);
    var ctx = canvas.getContext("2d");
    animate(0)
}
body {
    margin: 0;
}
#canvasOne {
    border:1px solid black;
}
<!DOCTYPE html>
<html>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
        <canvas id="canvasOne"></canvas>
</body>
</html>

编辑:由于某种原因,代码段在堆栈溢出时没有运行,所以这里是codePen页面的link:

https://codepen.io/Undefined_Variable/pen/aaWNJV

全屏查看并在每次向下 运行s 形状时刷新以查看问题。提前致谢!

好的,伙计们:我发现了问题:动画函数应该具有以下结构:

var rectY = 10;
function animate() {
    requestAnimationFrame(animate);
    new roundRect(10, rectY, 50, 7, "blue", "red", ctx);
    rectY += 1;
}

要绘制形状,回调应该是这样的:

animate();

可能没人在意,不过还是谢谢你哈哈