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);

Javascript - Loop through properties in an object(for .. in)

by sunil ravulapalli /4. January 2012 22:49 /javascript /Comments (0)

Quick Tip
If you want to loop through the properties in an object you can use the for..in loop construct.

var student = { 
    name:"tom",
    age:20
}; 

for (var key in student )
{
  document.write(key + ' = ' + student[key] + '
'); }

The above code will print:
name = tom
age = 20

Javascript - Variable without using the var keyword

by sunil ravulapalli /4. January 2012 22:39 /javascript /Comments (0)

Quick Tip
If you have a function like below where "temp" is declared and assigned without using the "var" keyword, it becomes a global variable!

function doSomething()
{
  temp=1;
}