我已经知道如何
-> 调整图像大小:
var image = document.getElementById('myImage'),
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
ctx.drawImage(image,0,0,400,300);
-> 或裁剪图像:
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);
但我不知道如何调整大小然后裁剪图像。我怎么能这样做呢?谢谢。
最佳答案
来自documentation ,这些是 drawImage
的参数:
drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
因此,要从源图像中裁剪外部 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)
示例:
const image = new Image(),
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
image.src = '/image/I4jXc.png';
image.addEventListener('load', () => {
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="/image/I4jXc.png" /><br/>
Canvas: <br/>
<canvas id="canvas" width="275px" height="95px"></canvas>
关于javascript - 如何使用 Canvas 调整图像大小然后裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26015497/