【问题标题】:Canvas transform rotation artifacts画布变换旋转伪影
【发布时间】:2018-02-09 14:00:49
【问题描述】:

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

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>

链接的矩形图像资源:

结果:

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

【问题讨论】:

  • 不知道究竟是为什么,但如果你这样做main.getContext("2d").clearRect(-1, -1, 600, 400); 它工作正常。
  • 哦,没关系。我发现:stackoverflow.com/a/21905707

标签: javascript html canvas transform image-rotation


【解决方案1】:

其实我发现了问题,看来变换矩阵对 clearRect() 方法也有影响,所以“清空区域”也被旋转了……

只需添加 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>

【讨论】:

  • 请注意,resetTransform() 在所有浏览器中都是not supported,您可以使用setTransform(1,0,0,1,0,0) 代替。我建议将上下文缓存到变量中。
  • 感谢兼容性信息!我用你的方法编辑我的答案
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2011-06-15
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2011-06-27
    • 2016-07-29
    • 1970-01-01
    相关资源
    最近更新 更多