微信小程序canvas绘制图片不变形的方法
程序员文章站
2024-03-04 15:06:35
...
项目中需要在canvas中绘制图片,图片大小未知
已这张图片为例
如果直接绘制图片将被压缩
根据官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/canvas/CanvasContext.drawImage.html
可以设定这些参数来保证图片不会变形
上代码:
wxml:
<view class="share">
<view style="padding-top: 65px, padding-bottom: 180rpx">
<view class="canvas" style="height: 475px">
<canvas canvas-id="firstCanvas"></canvas>
</view>
</view>
</view>
wxss:
.share{
width: 100%;
min-height: 100vh;
background: #000;
z-index: 132;
}
.canvas{
width: calc(100% - 60upx);
}
canvas{
width: 100%;
height: 100%;
margin-top: 30upx;
margin-left: 30upx;
overflow: hidden;
}
js:
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
},
onLoad() {
wx.showLoading({
title: '分享图生成中…'
})
let _this = this
setTimeout(function() {
_this.lotteryCanvas()
}, 500)
},
getImageInfo: function(url) {
return new Promise((resolve, reject) => {
wx.getImageInfo({
src: url,
success: function (res) {
resolve(res);
}, fail(res) {
reject('fail');
}
});
})
},
// 绘制canvas
lotteryCanvas: function() {
const query = wx.createSelectorQuery().in(this);
query.select('.canvas').boundingClientRect(res => {
console.log(res)
var ctx = wx.createCanvasContext('firstCanvas', this)
let canvasWidth = res.width
let canvasHeight = res.height
let thumb = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1602735806949&di=e064594d86b54c2addb3ba5f986ab4b7&imgtype=0&src=http%3A%2F%2Ft8.baidu.com%2Fit%2Fu%3D3571592872%2C3353494284%26fm%3D79%26app%3D86%26f%3DJPEG%3Fw%3D1200%26h%3D1290'
let getImageData = {}
// 获取图片
this.getImageInfo(thumb).then(res => {
getImageData.thumbImg = res
// 开始画图
ctx.save();
ctx.setFillStyle("#E8554E");//填充背景色
ctx.fillRect(0, 0, canvasWidth , canvasHeight );//画出矩形红色背景
// 绘制缩略图
this.drawImage(ctx, canvasWidth * 0.8, 150, getImageData.thumbImg.path, getImageData.thumbImg.width, getImageData.thumbImg.height, canvasWidth * 0.1, 160)
ctx.draw()
wx.hideLoading()
}).catch(res => {
console.log('获取缩略图失败')
})
}).exec();
},
/** 等比例图片方法
ctx 画布
bg_w 图片绘制区域的宽
bg_h 图片绘制区域的高
imgPath 图片路径
imgWidth 图片的原始宽度
imgPath 图片的原始高度
x 图片绘制的左上角x坐标
y 图片绘制的左上角y坐标
**/
drawImage(ctx, bg_w, bg_h, imgPath, imgWidth, imgHeight, x, y) {
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, x, y, bg_w, bg_h)
} else {
ctx.drawImage(imgPath, (imgWidth - bg_w/dHeight)/2, 0, bg_w/dHeight, imgHeight, x, y, bg_w, bg_h)
}
} else {
if (imgWidth < bg_w) {
ctx.drawImage(imgPath, 0, (imgHeight - bg_h/dWidth)/2, imgWidth, bg_h/dWidth, x, y, bg_w, bg_h)
} else {
ctx.drawImage(imgPath, (imgWidth - bg_w/dHeight)/2, 0, bg_w/dHeight, imgHeight, x, y, bg_w, bg_h)
}
}
}
})
最后的结果: