0
votes

I am creating a upload profile system where we are rotating the uploaded image using HTML5 canvas object using Javascript.

The uploaded image is rotating but the image is being cut always from any random side like little bit portion on bottom is cut or not drawn sometimes it is producing square image.

Here is the code below

function preview_image(event)
{
    var fileReader = new FileReader();
    fileReader.readAsDataURL(event.target.files[0]);
    fileReader.onload =function(event)
    {
        var canvas=document.createElement("canvas");
        var context=canvas.getContext("2d");

        var image = new Image();
        image.src=event.target.result;
        image.onload=function()
        {
            canvas.width=image.width;
            canvas.height=image.height;
            context.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);
            context.clearRect(0,0,canvas.width,canvas.height);
            context.save();
            context.translate(canvas.width/2,canvas.height/2);
            context.rotate(270*Math.PI/180);
            context.drawImage(image,-image.width/2,-image.width/2);
            context.restore();

            $('#img_div').prepend('<img id=main_img src='+canvas.toDataURL("image/jpg")+'>');
            document.getElementById("img_div").style.display="inline-block";
            document.getElementById("img_div").style.visibility="visible";
        }
    };
}

How to get full image after rotate using this solution i know i am missing some cordinates in drawimage functions fail to figure this out

Images are of variable width and height.

I also tried solution http://jsfiddle.net/m1erickson/6ZsCz/ but same cut image formed

1

1 Answers

0
votes

Try using this

var image=document.createElement("img");
image.onload=function(){

     var wrh = image.width / image.height;
        var newWidth = canvas.width;
        var newHeight = newWidth / wrh;
        if (newHeight > canvas.height) {
                    newHeight = canvas.height;
            newWidth = newHeight * wrh;
        }
        var xOffset = newWidth < canvas.width ? ((canvas.width - newWidth) / 2) : 0;
        var yOffset = newHeight < canvas.height ? ((canvas.height - newHeight) / 2) : 0;

        ctx.drawImage(image, xOffset, yOffset, newWidth, newHeight);
}