uni-app小程序封面图裁剪5/4比列
后台给到的图片过大或者过小分享出去的图片样式不是漂移就是缺失
<canvas canvas-id="canvas" style="position: absolute; top: -1000px; left: -1000px;width: 225px; height: 180px;"></canvas>
makeCanvas: function(imgUrl, title) {
uni.getImageInfo({
src: imgUrl,
success: (imgInfo) => {
let ctx = uni.createCanvasContext('canvas')
let canvasW = 0
let canvasH = imgInfo.height
// 把比例设置为 宽比高 5:4
canvasW = (imgInfo.height * 5) / 4
// 为画框设置背景色,注意要放在画图前,图会覆盖在背景色上
ctx.fillStyle = "#fff";
if (imgInfo.width > 225 || imgInfo.height > 180) {
canvasW = 225;
canvasH = 180;
ctx.fillRect(0, 0, canvasW, canvasH);
let dWidth = canvasW / imgInfo.width; // canvas与图片的宽度比例
let dHeight = canvasH / imgInfo.height; // canvas与图片的高度比例
let dWH = imgInfo.width / imgInfo.height; //宽高比
if (imgInfo.width > canvasW && imgInfo.height > canvasH) {
// console.log(dWH);
if (dWH > 1 && dWH < 1.5) {
ctx.drawImage(imgInfo.path, (canvasW - imgInfo.width * dHeight) / 2,
0, imgInfo.width * dHeight, imgInfo
.height *
dHeight)
} else {
if (imgInfo.width > imgInfo.height) {
ctx.drawImage(imgInfo.path, 0, (canvasH - imgInfo.height *
dWidth) / 2, imgInfo.width * dWidth,
imgInfo.height *
dWidth)
}
if (imgInfo.width == imgInfo.height) {
ctx.drawImage(imgInfo.path, (canvasW - imgInfo.width *
dHeight) / 2, 0, imgInfo.width * dHeight,
imgInfo
.height * dHeight)
}
if (imgInfo.width < imgInfo.height) {
ctx.drawImage(imgInfo.path, (canvasW - imgInfo.width *
dHeight) / 2, 0, imgInfo.width * dHeight,
imgInfo
.height * dHeight)
}
}
} else {
if (imgInfo.width > imgInfo.height) {
ctx.drawImage(imgInfo.path, 0, (canvasH - imgInfo.height) / 2,
imgInfo.width * dWidth, imgInfo.height)
}
if (imgInfo.width == imgInfo.height) {
ctx.drawImage(imgInfo.path, (canvasW - imgInfo.width * dHeight) / 2,
0, imgInfo.width * dHeight, imgInfo
.height *
dHeight)
}
if (imgInfo.width < imgInfo.height) {
ctx.drawImage(imgInfo.path, (canvasW - imgInfo.width * dHeight) / 2,
0, imgInfo.width * dHeight, imgInfo
.height *
dHeight)
}
}
} else {
ctx.fillRect(0, 0, canvasW, canvasH)
ctx.drawImage(
imgInfo.path,
0,
0,
canvasW,
canvasH,
(canvasW - imgInfo.width) / 2, // 宽度从中间向两边填充
0,
canvasW,
canvasH
)
}
ctx.draw(false, () => {
uni.canvasToTempFilePath({
width: canvasW,
height: canvasH,
destWidth: 750, // 标准的iphone6尺寸的两倍,生成高清图
destHeight: 600,
canvasId: "canvas",
fileType: "jpg", // 注意jpg默认背景为透明
success: (res) => {
this.shareImg = res.tempFilePath
this.shareInfo = {
title: title,
imageUrl: this.shareImg,
path: '/pages_vote/showRoomAskVotersDetail?from=share' +
'&pageUrl='+encodeURIComponent(this
.pageUrl)+'&userOptionId=' + this
.userOptionId + '&userQuestionId=' +
this
.userQuestionId + '&isCollention=' +
this.isCollention
};
},
fail: (err) => {
console.log("执行了", err)
}
})
})
}
})
},