使用html5画布旋转用户上传图片

时间:2019-07-09 09:32:40

标签: javascript jquery html html5-canvas

我正在创建一个上传配置文件系统,在该系统中,我们将使用Javascript使用HTML5 canvas对象旋转上载的图像。

上载的图像正在旋转,但是总是从任意随机的侧面剪切图像,例如底部的小部分被剪切或没有绘制,有时会产生方形图像。

这是下面的代码

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";
        }
    };
}

使用此解决方案旋转后如何获取完整图像我知道我在drawimage函数中缺少一些坐标

图像的宽度和高度都是可变的。

我也尝试了解决方法http://jsfiddle.net/m1erickson/6ZsCz/,但形成了相同的剪切图像

1 个答案:

答案 0 :(得分:0)

尝试使用

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