uniapp canvas 图片渲染变形的解决方法及使图片文字倾斜

文章讲述了在使用uniapp的canvas组件时,如何处理图片变形问题,通过调整drawImage函数参数以适应不同宽高比,并利用rotate和restore方法实现文本倾斜。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

图片变形:

当使用canvas渲染图片时,如果图片的宽高比例和咱们设置的不一样的话就会有图片变形的问题

那么解决的方法就是根据uniapp的drawImage(sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)渲染方式,动态的设定原图像的xy坐标以及矩形选择框的宽高

废话少说,直接贴代码

uni.downloadFile({
	url: _this.Img,
	success: function(res) {

       uni.getImageInfo({
          src: res.tempFilePath,
          success: function (image) {
             let imgPath = res.tempFilePath
             let imgWidth = image.width
             let imgHeight = image.height
             let bg_w = 300      // canvas图片的宽度
             let bg_h = 300    // canvas图片的高度
             let dWidth = bg_w / imgWidth;  // canvas与图片的宽度比例
             let dHeight = bg_h / imgHeight;  // canvas与图片的高度比例
             if (imgWidth > bg_w && imgHeight > bg_h || imgWidth < bg_w && imgHeight < bg_h) {
                 if (dWidth > dHeight) {
                    ctx.drawImage(imgPath, 0, (imgHeight - bg_h / dWidth) / 2, imgWidth, bg_h / dWidth, 0, 0, bg_w, bg_h)
                 } else {
                    ctx.drawImage(imgPath, (imgWidth - bg_w / dHeight) / 2, 0, bg_w / dHeight, imgHeight, 0, 0, bg_w, bg_h)
                 }
             } else {
                  if (imgWidth < bg_w) {
                    ctx.drawImage(imgPath, 0, (imgHeight - bg_h / dWidth) / 2, imgWidth, bg_h / dWidth, 0, 0, bg_w, bg_h)
                  } else {
                    ctx.drawImage(imgPath, (imgWidth - bg_w / dHeight) / 2, 0, bg_w / dHeight, imgHeight, 0, 0, bg_w, bg_h)
                  }
             }
             }});
       ctx.draw(true);
	}
});

倾斜:

使用ctx.rotate(Math.PI / 60)方法

使用ctx.restore()结束倾斜

uni.downloadFile({
						url: '图片路径',
						success: function(res) {
							ctx.rotate(Math.PI / 60);  // 角度:3度
							ctx.drawImage(res.tempFilePath,50,390, 80,23);    图片位置大小
							ctx.setFillStyle('#666'); // setFillStyle() 设置字体颜色
							ctx.setTextAlign('left')
							ctx.font = 'normal normal 12px arial,sans-serif';
							ctx.fillText('文案测试',50,430);
							ctx.draw(true);
                            ctx.restore();  // 恢复变换矩阵
						}
					});

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值