Search code examples
javascripthtmlcanvastransformimage-rotation

Canvas transform rotation artifacts


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 : the rectangle image resource

The result : enter image description here

Why does it generate all these artifacts?


Solution

  • 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>