微信小程序canvas绘制自适应图片,UniApp canvas绘制自适应图片

 需求:画布宽高为686 * 686 的正方形(可以进行调整根据自身需要来)

            当图片宽度大于高度时,对图片宽度进行裁剪

             当图片高度大于宽度时,对图片高度进行裁剪

             我是用uniApp进行开发的,如果是小程序原生,直接把“uni” 改为 “wx”’

<canvas style="width:686rpx, height:686rpx" type="2d"  canvas-id="firstCanvas" id="firstCanvas"></canvas>

 

init() {
				const query = uni.createSelectorQuery().select('#firstCanvas').fields({
					node: true,
					size: true
				}).exec((res) => {
                    //这里的代码不能少 适配start
					const canvas = res[0].node;
					const ctx = canvas.getContext('2d');
					const dpr = wx.getSystemInfoSync().pixelRatio
					canvas.width = res[0].width * dpr     // 获取宽
					canvas.height = res[0].height * dpr  // 获取高
					ctx.scale(dpr, dpr)
                    //这里的代码不能少 适配end
			
					
					// 绘制背景图片 , 
					ctx.beginPath();
					let imgDrawWidth = this.rpxToPx(686); // 图片绘制区域的宽度 (可以调整)
					let imgDrawHeight = this.rpxToPx(686); // 图片绘制区域的高度(可以调整)
					let canvasRatio = imgDrawWidth / imgDrawHeight;// 图片绘制区域的宽高比例
					let image = canvas.createImage(); //创建iamge实例
					image.src ='https://img0.baidu.com/it/u=1885009107,1276967789&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1677258000&t=6f5b311ecc21d4c80e5b932b95590ddd';
					// 图片的宽高比例
					image.onload = (e) => {
						console.log("height",image.height)
						console.log("width",image.width)
						let imgRatio = image.width / image.height;
						let dx, dy, dw, dh;
						if (imgRatio <= canvasRatio) {
							dw = image.width;
							dh = image.width;
							dx = 0;
							dy = (image.height - image.width) / 2;					
						} else { 
							dw = image.height;
							dh = image.height;
							dx = (image.width - image.height) / 2
							dy = 0;						
						}
						ctx.drawImage(image, dx, dy, dw, dh, 0,0,imgDrawWidth,imgDrawHeight) // 背景图  
					}
 				})
			},

 

			// rpx转px
			rpxToPx(rpx) {
				const screenWidth = uni.getSystemInfoSync().screenWidth
				return (screenWidth * Number.parseInt(rpx)) / 750
			},

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值