uniapp使用canvas绘制两张图片合并为一张图并保存至手机(H5+小程序)
需求: 访客二维码图片, 包含: 1二维码 2访客信息
1、二维码使用weapp-qrcode插件生成(canvas)
2、访客信息绘制到背景canvas上
3、最后,将二维码的canvas合并到背景canvas上。
js 部分:
listOwnerVisit(_objData).then((_visits) => { _that.visitInfo = _visits.visits[0];
// 以上为获取数据接口
// 开始绘制二维码 drawQrcode({ width: 200, height: 200, canvasId: 'myQrcode', text: this.visitInfo.qrCode, callback: (e) => { uni.canvasToTempFilePath({ x: 0, y: 0, width: 400, height: 400, destWidth: 400, destHeight: 400, canvasId: 'myQrcode', success: (qrcodeTempRes) => { // 获取到单二维码的tempFilePath // 将二维码的tempFilePath画到背景canvas上 uni.getSystemInfo({ success: (systemRes) => {
// 获取屏幕宽高 做居中用 this.windowWidth = systemRes.windowWidth; this.windowHeight = systemRes.windowHeight; let ctx = uni.createCanvasContext('myBg'); ctx.setFillStyle('#494949'); let topHeight = 0; // 二维码 ctx.drawImage(qrcodeTempRes.tempFilePath, this.windowWidth/2 - 100, topHeight += 20, 200, 200);// 列表名
// 以下为二维码下方要求显示的文本内容
ctx.setTextAlign('left'); ctx.setFontSize(14); ctx.setFillStyle('#A0A0A0'); ctx.fillText('访客姓名:', 10, topHeight += 20); ctx.fillText('访客联系方式:', 10, topHeight += 20); ctx.fillText('来访事由:', 10, topHeight += 20); ctx.fillText('车牌号:', 10, topHeight += 20); ctx.fillText('车辆审核状态:', 10, topHeight += 20); ctx.fillText('停车场:', 10, topHeight += 20); ctx.fillText('停车位:', 10, topHeight += 20); ctx.fillText('随行人数:', 10, topHeight += 20); ctx.fillText('预计来访时间:', 10, topHeight += 20); ctx.fillText('预计离开时间:', 10, topHeight += 20); ctx.fillText('备注:', 10, topHeight += 20);
// 绘制最终完整图
ctx.draw(true, () => { setTimeout(() => { // 获取到合并后的地址 uni.canvasToTempFilePath({ canvasId: 'myBg', fileType: 'jpg', success: (res2) => { this.tempFilePath = res2.tempFilePath //#ifdef H5 this.needLongTapSaveImg = true; //#endif } }) }) }) } }) } }) } }) })
html部分:
<view class="u-qrcode" style="text-align: center;"> <canvas style="width: 200px; height: 200px; margin: 0 auto;background: #fff;visibility: hidden;float: left;" canvas-id="myQrcode"></canvas> <canvas style="width: 100%; height: 600px; margin: 0 auto;background: #fff;" canvas-id="myBg" v-show="!needLongTapSaveImg"></canvas> <image :src="tempFilePath" style="width: 100%; height: 600px; margin: 0 auto;" v-show="needLongTapSaveImg"></image> </view>
1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类