简体   繁体   English

如何缩放画布上的图像大小

[英]How to scale resize an image on a canvas

I am currently trying to make an image upload tool, which allows you to crop an image before uploading it as a profile image. 我目前正在尝试制作图片上传工具,该工具可让您在将图片上传为个人资料图片之前裁剪图片。 The crop box is resizable, and whatever is within the bounds of the box is shown as a preview in a seperate canvas on the webpage. 裁剪框是可调整大小的,并且框范围内的所有内容都会在网页上单独的画布中显示为预览。 At the moment, I have the following code, which takes the area within the cropper on the first canvas (context) and places it on the second canvas (previewContext). 目前,我有以下代码,该代码将裁剪器中的区域放在第一个画布上(上下文),并将其放置在第二个画布上(previewContext)。

function previewCroppedImage() {
    var max_height = 100;
    var max_width = 100;
    var height = cropper.height;
    var width = cropper.width;
    var scale = Math.min(max_height/height, max_width/width)

    if (scale < 1) {
        height *= scale;
        width *= scale;
    }

    previewCropCanvas.width = width;
    previewCropCanvas.height = height;
    imgData = context.getImageData(cropper.x, cropper.y, width, height);
    previewContext.putImageData(imgData, 0, 0);

}

Using other questions, i have created this code. 使用其他问题,我创建了此代码。 However this code only takes the 100px X 100px area at the top left of the crop box, when that box is larger than 100 pixels. 但是,当该框大于100像素时,此代码仅占据裁剪框左上方的100px X 100px区域。 Instead, I want it to scale down the image data that it finds within the crop box, to 100 by 100px. 相反,我希望它将在裁剪框中找到的图像数据按比例缩小到100 x 100px。 I have shown what the tool currently looks like in the image below. 我已经在下图中显示了该工具当前的外观。

crop tool not working 裁剪工具不起作用

Try using the canvas ctx.scale function like this. 尝试像这样使用canvas ctx.scale函数。

ScaleHeight=maxHeight/height;
ScaleWidth=maxWidth/width;

Then either before you copy the picture to the new canvas or after its in the new canvas you can run 然后在将图片复制到新画布之前或之后在新画布中运行

ctx.scale(ScaleWidth,ScaleHeight);

ctx being the context of your canvas element The documentation for it can be found on the w3schools site ctx是画布元素的上下文,可以在w3schools网站上找到该文档的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM