Skip to content Skip to sidebar Skip to footer

Rotate Original Image With Jquery Or Javascript

Hello my doubts today is how can I rotate a photo, say no to just turn rotate the photo in a browser but doing a photo that was taken in portrait and landscape stand in different a

Solution 1:

If you wish to rotate canvas and keep the canvas the same size as the image when rotated (for example if you want to save out the image etc.) then you can simply set the canvas size for each time you rotate it.

A simple way of doing this is to store 90 degree increments in an array and use the index of the current angle of that array to determine what size (landscape /portrait) the canvas should be.

Sounds complicated? It's really simple:

/// store angles (0, 90, 180, 270) in an arrayvar angles = [0 * Math.PI, 0.5 * Math.PI, Math.PI, 1.5 * Math.PI],
    index = 0;

Now we have pre-calculated angles and the first angle is the originally orientation.

After the image has loaded we simply draw the image at whatever index we have, but we use the index to set the landscape/portrait mode by simply setting the canvas = image size if 0 or 180 degrees, and opposite for 90 and 270 degrees, ie, canvas height = image width and canvas width = image height.

Live demo

This makes sure the canvas is equal the size and orientation of the image when rotated.

function renderImage() {

    /// use index to set canvas sizeswitch(index) {
        case0:
        case2:
            /// for 0 and 180 degrees size = image
            canvas.width = img.width;
            canvas.height = img.height;
            break;
        case1:
        case3:
            /// for 90 and 270 canvas width = img height etc.
            canvas.width = img.height;
            canvas.height = img.width;
            break;
    }

    /// get stored angle and center of canvas    var angle = angles[index],
        cw = canvas.width * 0.5,
        ch = canvas.height * 0.5;
    
    /// rotate context
    ctx.translate(cw, ch);
    ctx.rotate(angle);
    ctx.translate(-img.width * 0.5, -img.height * 0.5);
    
    /// draw image and reset transform
    ctx.drawImage(img, 0, 0);
    ctx.setTransform(1, 0, 0, 1, 0, 0);
}

To rotate the image just hook of the following code to the buttons:

/// rotate counter-clock-wise (CCW)
function rotateCCW() {
    index--;      /// decrement index of array
    if (index < 0) index = angles.length -1;
    renderImage();
}

/// rotate clock-wise (CW)
function rotateCW() {
    index++;     /// increment index of array
    if (index >= angles.length) index = 0;
    renderImage();
}

Post a Comment for "Rotate Original Image With Jquery Or Javascript"