如何缩放画布上的图像大小 [英] How to scale resize an image on a canvas
问题描述
我目前正在尝试制作图片上传工具,该工具可让您在将图片上传为个人资料图片之前裁剪图片。裁剪框是可调整大小的,并且框范围内的所有内容都会在网页上单独的画布中显示为预览。目前,我有以下代码,该代码将第一个画布上的裁切器内的区域(上下文)放在第二个画布上(previewContext)。
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).
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);
}
使用其他问题,我创建了此代码。但是,当该框大于100像素时,此代码仅占据裁剪框左上方的100px X 100px区域。相反,我希望它将在裁剪框中找到的图像数据按比例缩小到100 x 100px。我已经在下图中显示了该工具的当前外观。
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. Instead, I want it to scale down the image data that it finds within the crop box, to 100 by 100px. I have shown what the tool currently looks like in the image below.
推荐答案
尝试像这样使用canvas ctx.scale函数。
Try using the canvas ctx.scale function like this.
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
这篇关于如何缩放画布上的图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!