HTML Canvas Rotate Image

by sunil ravulapalli /22. January 2013 04:08 /javascript /Comments (0)

The following is a function to rotate an image using javascript on html canvas:

    
    function rotateImage(img, x, y, width, height, deg) {

        //Convert degrees to radian 
        var rad = deg * Math.PI / 180;

        //Set the origin to the center of the image
        ctx.translate(x + width, y + height);

        //Rotate the canvas around the origin
        ctx.rotate(rad);

        //draw the image    
        ctx.drawImage(img, width * (-1), height * (-1), width, height);

        //reset the canvas  
        ctx.rotate(rad * (-1));
        ctx.translate((x + width) * (-1), (y + height) * (-1));
    }

It can be used a follows:

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

    var img = new Image();
    img.src = "fish.png";

    rotateImage(img, 50, 50, 100, 100, 45);
blog comments powered by Disqus