实现效果:
按照比例居中裁剪,如下图所示:


实现思路:
- 设置一个固定的图片宽度和高度
- 根据设置的固定宽高算出图片比例
- 通过getImageInfo获取需要绘制的图片的信息
- 根据不同情况算出绘制图片时上图所需的各种参数
//图片宽高
let imageInfo = {
width: 300,
height: 340
};
//图片比例
let scale = imageInfo.width / imageInfo.height;
//获取图片信息
let res = await this.getImageInfo(imgUrl);
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);
通过上面几种计算结果,就能绘制出适配各种比例的居中裁剪图片啦
1万+

被折叠的 条评论
为什么被折叠?



