Canvas 变换旋转工件

Canvas transform rotation artifacts

我得到了这个使简单图像旋转的小代码

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>

链接的矩形图像资源:

结果:

为什么它会生成所有这些工件?

实际上我发现了问题,似乎变换矩阵也对 clearRect() 方法有影响,所以 "clearing area" 也被旋转了...

只需添加 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";
<body>
<canvas id="main" width=600 height=400></canvas>
</body>

根据@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>