canvas rotate image

canvas rotate image

by pj_js15

HTML

<canvas id="canvas" width=300 height=300></canvas><br>
<button id="clockwise">Rotate right</button>
<button id="counterclockwise">Rotate left</button>

CSS

body{ background-color: ivory; }
canvas{border:1px solid red;}

JavaScript

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var angleInDegrees=0;

var image=document.createElement("img");
image.onload=function(){
    ctx.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);
}
image.src="https://www.google.com.au/logos/doodles/2018/world-cup-2018-day-6-5186186996875264-s.png";

$("#clockwise").click(function(){ 
    angleInDegrees+=90;
    drawRotated(angleInDegrees);
});

$("#counterclockwise").click(function(){ 
    angleInDegrees-=90;
    drawRotated(angleInDegrees);
});

function drawRotated(degrees){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.save();
    ctx.translate(canvas.width/2,canvas.height/2);
    //ctx.translate(canvas.width,canvas.height);
    ctx.rotate(degrees*Math.PI/180);
    ctx.drawImage(image,-image.width/2,-image.height/2);
    //ctx.drawImage(image,100,0);
    ctx.restore();
}