Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. arjankuijpers created this gist Aug 31, 2013.
    29 changes: 29 additions & 0 deletions rotate image in canvas with javascript HTML5
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    var canvas;
    var ctx;


    var gameDiv =document.getElementById('game');
    canvas =document.createElement("canvas");
    gameDiv.appendChild(canvas);

    canvas.width = 600;
    canvas.height = 475;
    ctx=canvas.getContext("2d");

    odin = new Image();
    odin.src = "http://devimages.apple.com/iphone/gamecenter/images/hero-gamecenter.jpg";

    odin.onload = function(){
    //draw function

    //you could save here cordination system of the context with ctx.save();

    ctx.drawImage(odin, 50,50); // image without rotation
    //ctx.clearRect(0,0,canvas.width, canvas.height); // dont clear the example image
    ctx.translate( 50 + (odin.width /2), 50 + (odin.height /2)); // set orgin 0,0 of context to the center of the image
    ctx.rotate(Math.PI * 0.75 ); // rotate the context it will rotate from the orgin
    ctx.drawImage(odin,-odin.width /2,-odin.height /2); // draw the rotated image.

    //you could now do ctx.restore to the original translate and rotate.

    }