Search code examples
javascripthtmlcanvas

Rotate Canvas content


I've made an image editor, where i can upload an image to crop.

Now I should rotate this image but I'm not able to do this.

I've found some snippet to rotate a canvas but I can't see result, canvas doesn't rotate.

ctx.translate(50,50);
ctx.rotate(angle / 180 / Math.PI);
ctx.drawImage(orig_src, -16, -16);
ctx.restore();

I'm new in HTML/JavaScript so maybe there's something wrong in the code.

Here is the code: https://jsfiddle.net/marcom89/awb7320h/1/


Solution

  • It works after little fixing save/restore & clearing canvas (clearRect), also, calling "drawImage" directly inside method.

    fiddle: here

        ctx.clearRect(0, 0, resize_canvas.width, resize_canvas.height);
        ctx.save();
        ctx.translate(resize_canvas.width/2,resize_canvas.height/2);
        ctx.rotate(angle / 180 / Math.PI);
        ctx.drawImage(orig_src, -resize_canvas.width/2, -resize_canvas.height/2);
        ctx.restore();
    

    It's not straight probably because you're translating canvas without save/restore. Actions like translate& rotate could mess up every following operation, so remember to save/restore in most cases.