![](/img/trans.png)
[英]Canvas crop: resize image, mantain aspect ration and center? JsFiddle
[英]Canvas image resize and then crop center
您可以使用drawImage 。 即最后一个选项,您指定源点和目标点以抓取图像的一部分,然后将该部分绘制到 canvas。
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
然后,您只需要获取高度的中心并从中减去您的尺寸,然后绘制完整尺寸。
void ctx.drawImage(image, 0, (height / 2) - size, sWidth, size, dx, dy, dWidth, size);
const image = new Image(); image.src = 'https://i.picsum.photos/id/315/200/200.jpg?hmac=cE5OEQSh9gvXqkP0fkrmaSbqLfc_KQdDPtH7yBbeuiQ'; const canvas = document.querySelector('canvas'); canvas.width = canvas.height = 300; const ctx = canvas.getContext('2d'); function cropMiddle(image, size) { const height = image.height; const width = image.width; const center = height / 2; ctx.drawImage(image, 0, center - size, width, size, 0, 0, width, size); } // Wait until the image is loaded image.addEventListener('load', () => { cropMiddle(image, 100); });
<canvas></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.