画布旋转功能创建空白图像

时间:2019-04-17 03:43:25

标签: jquery html5-canvas image-manipulation exif-js

嗨,我正在使用canvas和base64字符串调整图像大小并压缩图像

这是完整的代码

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

        }

    };

}

我想将图像旋转90度,但是在使用jpgurl创建图像之后,输出图像仍然没有旋转并且空白

1 个答案:

答案 0 :(得分:1)

旋转的图像不在屏幕上。如果要围绕图像中心旋转图像,请尝试以下操作:

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

        }

    };

}

有两个更改:

1)在旋转画布之前平移原点

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

2)绘制图像,使其中心位于原点上方。

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

请记住,画布将保持旋转,并且其原点将位于其中心。如果想返回,可以在context.save()之前放置translate,在context.restore()之后放置drawImage