How to scale resize an image on a canvas

强颜欢笑 提交于 2020-04-21 04:38:01

问题


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

}

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.

crop tool not working


回答1:


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



来源:https://stackoverflow.com/questions/34679070/how-to-scale-resize-an-image-on-a-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!