图片变形:
当使用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(); // 恢复变换矩阵
}
});