【问题标题】:Rotate user upload image using html5 canvas使用 html5 画布旋转用户上传图像
【发布时间】:2019-11-18 19:57:32
【问题描述】:

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

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

下面是代码

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

如何在使用此解决方案旋转后获取完整图像

图像具有可变的宽度和高度。

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

【问题讨论】:

    标签: javascript jquery html html5-canvas


    【解决方案1】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 2011-03-14
      相关资源
      最近更新 更多