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



嗨,我正在使用画布和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 创建图像后,输出图像仍然没有旋转且空白

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

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

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

相关内容

  • 没有找到相关文章

最新更新