Javascript 如何使用画布调整大小然后裁剪图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26015497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:12:12  来源:igfitidea点击:

How to resize then crop an image with canvas

javascripthtml5-canvas

提问by Lewis

I already know how to

我已经知道如何

-> resize an image:

-> 调整图像大小:

var image = document.getElementById('myImage'),
    canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');
ctx.drawImage(image,0,0,400,300);

-> or crop an image:

-> 或裁剪图像:

var image = document.getElementById('myImage'),
    canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');
ctx.drawImage(image,50,50,image.width,image.height,0,0,50,50);

But I don't know how to resize then crop an image. How could I do this? Thank you.

但我不知道如何调整大小然后裁剪图像。我怎么能这样做?谢谢你。

回答by Cerbrus

From the documentation, these are the parameters for drawImage:

文档中,这些是以下参数drawImage

drawImage(image,
    sx, sy, sw, sh,
    dx, dy, dw, dh);

enter image description here

drawImage(image,
    sx, sy, sw, sh,
    dx, dy, dw, dh);

在此处输入图片说明

So, to crop the outer 10 pixels from the source image (Assuming it's 100 * 50), and then to scale that up to 160*60:

因此,要从源图像中裁剪外部 10 个像素(假设它是100 * 50),然后将其放大到160*60

ctx.drawImage(image,
    10, 10,   // Start at 10 pixels from the left and the top of the image (crop),
    80, 30,   // "Get" a `80 * 30` (w * h) area from the source image (crop),
    0, 0,     // Place the result at 0, 0 in the canvas,
    160, 60); // With as width / height: 160 * 60 (scale)

Example:

例子:

var image = new Image(),
    canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');

image.src = 'https://i.stack.imgur.com/I4jXc.png';

image.onload = function(){
    ctx.drawImage(image,
        70, 20,   // Start at 70/20 pixels from the left and the top of the image (crop),
        50, 50,   // "Get" a `50 * 50` (w * h) area from the source image (crop),
        0, 0,     // Place the result at 0, 0 in the canvas,
        100, 100); // With as width / height: 100 * 100 (scale)
}
Image: <br/>
<img src="https://i.stack.imgur.com/I4jXc.png" /><br/>
Canvas: <br/>
<canvas id="canvas" width="275px" height="95px"></canvas>

回答by Jim

Before drawing onto the canvas, specify the final canvas size with canvas.width and canvas.height otherwise the final will always be 300x150

在画布上绘制之前,使用 canvas.width 和 canvas.height 指定最终画布大小,否则最终将始终为 300x150