```// 创建画布区域
let context = uni.createCameraContext('posterCanvas');
// 获取屏幕的消息
let systemInfo = new Promise((res, rej) => {
uni.getSystemInfo({
success: (data) => {
res(data);
}
});
});
systemInfo.then(systemInfo => {
// 获取不同设备的宽高适配
let {
windowWidth,
windowHeight
} = systemInfo;
let rpx = 1;
// 个性化定义针对不同设备的单位比率,和标准设计稿375比较
rpx = windowWidth / 375;
context.clearRect(0, 0, 279 * rpx, 385 * rpx);
//设置海报背景为白色
context.fillStyle = "#fff";
// 填充背景颜色
context.fillRect(0, 0, 279 * rpx, 385 * rpx);
let path = this.posterBanner; // posterbanner是一个固定的图片链接
let imagePromise = [img1, img2];
imagePromise = imagePromise.map(src => {
return new Promise((res, rej) => {
//不获取一下图片信息会导致图片在真机上绘制失败
uni.getImageInfo({
src,
success: data => {
console.log("imgdata--->", data);
res(data);
},
fail(err) {
console.log("err", err);
}
});
});
});
Promise.all(imagePromise).then(imgsInfo => {
context.drawImage(
imgsInfo[0].path,
12.5 * rpx,
12.5 * rpx,
254 * rpx,
173 * rpx
);
context.setFontSize(14 * rpx);
context.setTextAlign("center");
context.setFillStyle("#390C59");
context.fillText(
"xxxxxxxxxxxx一段文字",
(279 * rpx) / 2,
205.5 * rpx
);
context.setFontSize(14 * rpx);
context.setTextAlign("center");
context.setFillStyle("#390C59");
context.fillText("xxxx一段文字!", (279 * rpx) / 2, 226.5 * rpx);
context.drawImage(
imgsInfo[1].path,
102 * rpx,
262.5 * rpx,
75 * rpx,
75 * rpx
);
context.setFontSize(12 * rpx);
context.setTextAlign("center");
context.setFillStyle("#390C59");
context.fillText("长按扫码查看详情", (279 * rpx) / 2, 360.5 * rpx);
context.draw(false, () => {
//因为draw是异步的,移动端偶发绘制文字丢失,所以增加settimeout
setTimeout(() => {
uni.canvasToTempFilePath({
canvasId: "posterCanvas",
destWidth: 558 * 2,
destHeight: 770 * 2,
success(res) {
//拿到生成的画布图片临时路径在res.tempFilePath中,可以自行存储或者赋值
}
});
}, 100);
});
});
})