donm
donm

Reputation: 67

Canvas rotate function creates blank image

Hi i am resizing and compressing the image using canvas and base64 string

here is the full code

function preview_image(event)
{
    var fileReader = new FileReader();
    fileReader.onload = function (event)
    {
        var image = new Image();
        image.onload=function()
        {
            var canvas=document.createElement("canvas");
            var context=canvas.getContext("2d");
            canvas.width=600;
            canvas.height=canvas.width*image.height/image.width; /*For Aspect ratio*/

            context.rotate(90 * Math.PI/180); // rotate by 90 degrees

context.drawImage(image,0,0,image.width,image.height,0,0,canvas.width,canvas.height);

            var jpgurl=canvas.toDataURL('image/jpeg', 0.5);

        }

    };

}

I want to rotate the image to 90 degree but after creating the image using the jpgurl the output image is still not rotated and blank

Upvotes: 1

Views: 228

Answers (1)

R. Schifini
R. Schifini

Reputation: 9313

The rotated image is offscreen. If you want to rotate an image around its center try this:

function preview_image(event)
{
    var fileReader = new FileReader();
    fileReader.onload = function (event)
    {
        var image = new Image();
        image.onload=function()
        {
            var canvas=document.createElement("canvas");
            var context=canvas.getContext("2d");
            canvas.width=600;
            canvas.height=canvas.width*image.height/image.width; /*For Aspect ratio*/

            // First move the origin (0,0) to the middle of the canvas
            context.translate(canvas.width/2, canvas.height/2)

            context.rotate(90 * Math.PI/180); // rotate by 90 degrees

            // And also draw the Image centered on the origin
            context.drawImage(image, -image.width/2, -image.height/2, image.width/2, image.height/2, 0, 0, canvas.width, canvas.height);


            var jpgurl=canvas.toDataURL('image/jpeg', 0.5);

        }

    };

}

There are two changes:

1) Translate the origin before rotating the canvas

context.translate(canvas.width/2, canvas.height/2)

2) Draw the image with its center on top of the origin.

context.drawImage(image, -image.width/2, -image.height/2,
 image.width/2, image.height/2, 0, 0, canvas.width, canvas.height);

Remember that the canvas will stay rotated and its origin will be at its center. If you want to go back you could place a context.save() before the translate and a context.restore() after the drawImage

Upvotes: 1

Related Questions