Reputation: 122
I got this little code that makes a simple image rotate
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.sstatic.net/gCWW9.png";
<body>
<canvas id="main" width=600 height=400></canvas>
</body>
The linked rectangle image resource :
Why does it generate all these artifacts?
Upvotes: 1
Views: 145
Reputation: 122
Actually I found out the problem, it appears that the transform matrix also have effect on the clearRect() method so the "clearing area" is rotated as well...
Just had to add setTransform(1,0,0,1,0,0) that resets the transform matrix before calling clearRect() like so:
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.sstatic.net/gCWW9.png";
<body>
<canvas id="main" width=600 height=400></canvas>
</body>
Upvotes: 2
Reputation: 2264
Based on @GolfWolf's comment I use the following code it works.
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.sstatic.net/gCWW9.png";
<body>
<canvas id="main" width=600 height=400></canvas>
</body>
Upvotes: 0