我得到了这个简单的图像旋转的小代码
var img = new Image(50, 200);
img.addEventListener("load", (e) => {
setInterval(function() {
main.getContext("2d").clearRect(0, 0, 600, 400);
main.getContext("2d").rotate(-1 * Math.PI / 180);
main.getContext("2d").drawImage(img, 0, 0, 50, 200, 0, 0, 50, 200);
}, 50);
});
img.src = "https://i.stack.imgur.com/gCWW9.png";

<body>
<canvas id="main" width=600 height=400></canvas>
</body>
&#13;
为什么会生成所有这些工件?
答案 0 :(得分:1)
实际上我发现了问题,似乎变换矩阵也对clearRect()方法有影响所以&#34;清除区域&#34;旋转也是......
只需添加setTransform(1,0,0,1,0,0),在调用clearRect()之前重置转换矩阵,如下所示:
var rotation=0;
var img = new Image(50, 200);
img.addEventListener("load", (e) => {
setInterval(function() {
rotation--;
main.getContext("2d").setTransform(1,0,0,1,0,0); //that line was missing
main.getContext("2d").clearRect(0, 0, 600, 400);
main.getContext("2d").rotate(rotation * Math.PI / 180);
main.getContext("2d").drawImage(img, 0, 0, 50, 200, 0, 0, 50, 200);
}, 50);
});
img.src = "https://i.stack.imgur.com/gCWW9.png";
&#13;
<body>
<canvas id="main" width=600 height=400></canvas>
</body>
&#13;
答案 1 :(得分:0)
基于@GolfWolf的评论,我使用以下代码。
var img = new Image(50, 200);
img.addEventListener("load", (e) => {
setInterval(function() {
main.getContext("2d").clearRect(-0.5, -0.5, 600, 400);
main.getContext("2d").rotate(-1 * Math.PI / 180);
main.getContext("2d").drawImage(img, 0, 0, 50, 200, 0, 0, 50, 200);
}, 50);
});
img.src = "https://i.stack.imgur.com/gCWW9.png";
<body>
<canvas id="main" width=600 height=400></canvas>
</body>