我在 setInterval 方法中有一个矩形,并使用旋转方法,它按预期旋转,但是当我在矩形上方添加另一个元素时,它也会旋转。我尝试将其作为单独的函数取出,但似乎所有元素都继承了旋转。
<!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>
最佳答案
您正在旋转变换矩阵。你需要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>
关于javascript - 旋转方法使所有东西旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54450624/