mergeImage: function (src) {
const query = wx.createSelectorQuery();
query
.select('#canvsaMerger')
.fields({
node: true,
size: true,
})
.exec((res) => {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
const dpr = 2;
// 创建第一张图片
const img1 = canvas.createImage();
img1.src = src;
// 创建第二张图片
const img2 = canvas.createImage();
img2.src = './images/qr-code.png';
// 确保两张图片都加载完成
Promise.all([
new Promise((resolve) => {
img1.onload = resolve;
}),
new Promise((resolve) => {
img2.onload = resolve;
}),
]).then(() => {
let img1Width = img1.width;
let img1Height = img1.height;
// 保持第二张图片的宽高比
let img2Height = img1Width * (img2.height / img2.width);
// 动态计算 OFFSET
const OFFSET = img1Width * 0.2;
// 设置 canvas 临时大小
let canvasWidth = img1Width;
let canvasHeight = img1Height + img2Height - OFFSET;
const maxSize = 3000
// 检查是否需要缩放以保持在最大尺寸范围内
let scaleFactor = 1;
if (canvasWidth * dpr > maxSize || canvasHeight * dpr > maxSize) {
scaleFactor = Math.min(maxSize / (canvasWidth * dpr), maxSize / (canvasHeight * dpr));
}
// 将比例因子应用于画布和图像尺寸
canvasWidth = canvasWidth * scaleFactor;
canvasHeight = canvasHeight * scaleFactor;
img1Width = img1Width * scaleFactor;
img1Height = img1Height * scaleFactor;
img2Height = img2Height * scaleFactor;
// 设置实际画布大小,考虑设备像素比
canvas.width = canvasWidth * dpr;
canvas.height = canvasHeight * dpr;
console.log(canvasWidth, canvasHeight, canvas.width, canvas.height, 'canvas.height')
// 上下文已缩放以考虑 DPR
ctx.scale(dpr, dpr);
// 绘制第一张图像
ctx.drawImage(img1, 0, 0, img1Width, img1Height);
// 将第二张图像绘制在第一张图像下方,并带有偏移量
ctx.drawImage(img2, 0, img1Height - OFFSET * scaleFactor, img1Width, img2Height);
wx.nextTick(() => {
wx.canvasToTempFilePath({
canvas: canvas,
x: 0,
y: 0,
width: canvas.width,
height: canvas.height,
destWidth: canvasWidth,
destHeight: canvasHeight,
fileType: 'png',
quality: 0.01,
success: (res) => {
console.log(res.tempFilePath, 'res.tempFilePath1111')
// wxfile://tmp_54f0f65f3d69825d65c873a7ac502f9d.png
wx.showShareImageMenu({
path: res.tempFilePath,
success: function (res) {
console.log(res, '2-2-2-')
},
fail: function (e) {
console.log(e, '20202020')
},
complete: function (e) {
console.log(e, '20202p2p')
},
});
},
fail: (err) => {
console.error('导出图片失败', err);
},
}, this);
})
});
});
},
请具体描述问题出现的流程,并提供能复现问题的简单代码片段(https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html)。
图太大了,尝试缩小试试看。