旋转方法使一切旋转

时间:2019-01-30 22:38:02

标签: javascript html5 canvas html5-canvas

我在setInterval方法中有一个矩形,使用rotation方法,它会按预期旋转,但是当我在矩形上方添加另一个元素时,它也会旋转。我尝试将其作为单独的函数拉出,但似乎所有元素都继承了旋转。

<!DOCTYPE html>
<html>
<body>
<canvas id="paper" width="500" height="500"></canvas>
</body>
<script>
window.onload = function(){

var canvas = document.getElementById("paper"),
c = canvas.getContext("2d");

c.fillStyle = "#00ffff";
c.fillRect(0,0,500,500);

c.translate(250,250);

c.fillStyle = "#ff0000";
c.beginPath();
c.arc(100,100,10,0,Math.PI*2,false);
c.fill();

c.fillStyle = "#ff0000";
c.fillRect(0,0,2,500);



setInterval(function(){

 c.fillStyle = "#00ffff";
 c.fillRect(0,0,500,500);

 c.fillStyle = "#ff0000";
 c.beginPath();
 c.arc(100,100,10,0,Math.PI*2,false);
 c.fill();

 c.rotate(.01);
 c.fillStyle = "#ff0000";
 c.fillRect(0,0,2,500);

},30);

};

</script>
</html>

1 个答案:

答案 0 :(得分:1)

您正在旋转变换矩阵。您需要在旋转之前save状态,在绘制之后restore状态。

示例:

    window.onload = function () {

        var canvas = document.getElementById("paper"),
            c = canvas.getContext("2d");

        c.fillStyle = "#00ffff";
        c.fillRect(0, 0, 500, 500);

        c.translate(250, 250);

        c.fillStyle = "#ff0000";
        c.beginPath();
        c.arc(100, 100, 10, 0, Math.PI * 2, false);
        c.fill();

        c.fillStyle = "#ff0000";
        c.fillRect(0, 0, 2, 500);

        // radians
        var angle = 0;

        setInterval(function () {

            c.fillStyle = "#00ffff";
            c.fillRect(0, 0, 500, 500);

            c.fillStyle = "#ff0000";
            c.beginPath();
            c.arc(100, 100, 10, 0, Math.PI * 2, false);
            c.fill();

            // saving current state
            c.save();
            c.rotate(angle += .01);
            c.fillStyle = "#ff0000";
            c.fillRect(0, 0, 2, 500);
            // restore previous state
            c.restore();

        }, 30);

    };
<canvas id="paper" width="500" height="500"></canvas>