代码之家  ›  专栏  ›  技术社区  ›  Saif Taher

在HTML5画布上移动的形状,而它们不应该:requestAnimationFrame()

  •  1
  • Saif Taher  · 技术社区  · 7 年前

    滚筒

    当我传递创建矩形对象的函数并将它们设置为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>

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

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   Saif Taher    7 年前

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

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

    要画一个形状,回调应该是这样的:

    animate();
    

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