{ setInterval-6ren">
gpt4 book ai didi

javascript - Canvas 变换旋转工件

转载 作者:行者123 更新时间:2023-11-30 20:45:58 25 4
gpt4 key购买 nike

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

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 = "/image/gCWW9.png";
<body>
<canvas id="main" width=600 height=400></canvas>
</body>

链接的矩形图像资源: the rectangle image resource

结果:enter image description here

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

最佳答案

实际上我发现了问题,似乎变换矩阵也对 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 = "/image/gCWW9.png";
<body>
<canvas id="main" width=600 height=400></canvas>
</body>

关于javascript - Canvas 变换旋转工件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48707606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com