实现效果:
按照比例居中裁剪,如下图所示:
;
let imgX = 0;
let imgY = (res.height - (res.width / imageInfo.width) * imageInfo.height) / 2;
let imgWidth = res.width;
let imgHeight = (res.width / imageInfo.width) * imageInfo.height;
- 当图片比例等于3:2
if (res.width / res.height < scale) {
//居中裁剪高
ctx.drawImage(res.path, imgX, imgY, imgWidth, imgHeight, 0, 0, imageInfo.width, imageInfo.height);
}
- 当图片比例大于3:2
`if (res.width / res.height == scale) {
imgY = 0;
imgWidth = imageInfo.width;
imgHeight = res.height / (res.width / imageInfo.width);
ctx.drawImage(res.path, imgX, imgY, imgWidth, imgHeight);
}`
- 当图片比例小于3:2
{
imgX = (res.width - (res.height / imageInfo.height) * imageInfo.width) / 2;
imgY = 0;
imgHeight = res.height;
imgWidth = (res.height / imageInfo.height) * imageInfo.width;
ctx.drawImage(res.path, imgX, imgY, imgWidth, imgHeight, 0, 0, imageInfo.width, imageInfo.height);
通过上面几种计算结果,就能绘制出适配各种比例的居中裁剪图片啦