简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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