canvas绘图之图片居中裁剪

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

List item

![在这里插入图片描述](https://img-blog.csdnimg.cn/7d7ee4cafa1b4ed5b46aeb9f5c611572.pngAPI应用:在这里插入图片描述
实现思路:

  1. 设置一个固定的图片宽度和高度
  2. 根据设置的固定宽高算出图片比例
  3. 通过getImageInfo获取需要绘制的图片的信息
  4. 根据不同情况算出绘制图片时上图所需的各种参数
//图片宽高
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;
  1. 当图片比例等于3:2
if (res.width / res.height < scale) {
				//居中裁剪高
				ctx.drawImage(res.path, imgX, imgY, imgWidth, imgHeight, 0, 0, imageInfo.width, imageInfo.height);
			}
  1. 当图片比例大于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);
			}`
  1. 当图片比例小于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);

通过上面几种计算结果,就能绘制出适配各种比例的居中裁剪图片啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值