当前位置: 首页 > news >正文

微信小程序-二维码绘制

wxml

<view bindlongtap="saveQrcode"><!-- 二维码 --><view style="position: absolute;background-color: #FFFAEC;width: 100%;height: 100vh;"><canvas canvas-id="myQrcode" style="width: 200px; height: 200px;background-color: azure;position: fixed;top: 999px;" ></canvas></view><!-- 绘制的背景图 --><canvas type="2d" id="newQrcode" style="width: 100%;height: 700px;z-index: 99;"></canvas>
</view>

wxss

/* pages/QRcode/QRcode.wxss */
.canvas {width: 100%;height: -webkit-calc(100% - 44px);height: -moz-calc(100% - 44px);height: calc(100% - 44px);background: #fff;}

js

// pages/index/index.js
import QRCode from './weapp.qrcode.esm';let textCanvas;Page({data: {qrcodeVisible: true // 控制二维码是否显示},onReady() {// 等待二维码绘制完成后再获取临时文件路径this.generateQRCode().then((tempQrcodePath) => {this.drawCompositeImage(tempQrcodePath);}).catch((err) => {console.error('生成二维码临时文件失败:', err);wx.showToast({title: '生成二维码临时文件失败',icon: 'none'});});},// 生成二维码并获取临时文件路径generateQRCode() {return new Promise((resolve, reject) => {// 初始化二维码QRCode({width: 200,height: 200,canvasId: 'myQrcode',colorDark: '#000000',colorLight: '#ffffff',text: 'http://lxj.yzwdblzs.xyz/',});// 延迟一段时间确保二维码绘制完成,可根据实际情况调整延迟时间setTimeout(() => {wx.canvasToTempFilePath({canvasId: 'myQrcode',success: (res) => {console.log('二维码路径:', res);const tempQrcodePath = res.tempFilePath;resolve(tempQrcodePath);},fail: (err) => {console.error('获取临时文件失败', err);reject(err);}});}, 500);});},drawCompositeImage(tempQrcodePath) {return new Promise((resolve, reject) => {wx.createSelectorQuery().select('#newQrcode').fields({node: true,size: true}).exec((res) => {textCanvas = res[0].node; // 获取 canvas 节点const textCtx = textCanvas.getContext('2d');const dpr = wx.getSystemInfoSync().pixelRatio; // 获取设备像素比textCanvas.width = res[0].width * dpr;textCanvas.height = res[0].height * dpr;textCtx.scale(1, 1);textCtx.fillRect(0, 0, 200, 200);textCtx.clearRect(0, 0, textCanvas.width, textCanvas.height);textCtx.beginPath();const bg = textCanvas.createImage();bg.src = 'http://lxj.yzwdblzs.xyz/img/noName.png';bg.onload = () => {console.log('背景图加载成功');const qrImage = textCanvas.createImage();qrImage.src = tempQrcodePath;qrImage.onload = () => {console.log('二维码加载成功');// 绘制背景图this.drawBackground(textCtx, bg);// 绘制二维码this.drawQRCode(textCtx, tempQrcodePath);resolve();};qrImage.onerror = () => {console.error('二维码加载失败');reject(new Error('二维码加载失败'));};};bg.onerror = () => {console.error('背景图加载失败');reject(new Error('背景图加载失败'));};});});},drawBackground(textCtx, bg) {const bgWidth = bg.width;const bgHeight = bg.height;// 计算缩放比例const scaleX = textCanvas.width / bgWidth;const scaleY = textCanvas.height / bgHeight;const scale = Math.max(scaleX, scaleY); // 选择最大的比例以适应 canvas// 计算背景图绘制的尺寸const drawWidth = bgWidth * scale;const drawHeight = bgHeight * scale;// 绘制背景图textCtx.drawImage(bg, 0, 0, drawWidth, drawHeight);},drawQRCode(textCtx, tempQrcodePath) {const qrWidth = 550; // 二维码宽度const qrHeight = 550; // 二维码高度const qrX = (textCanvas.width - qrWidth + 40) / 2; // 水平居中const qrY = (textCanvas.height - qrHeight + 940) / 2; // 垂直居中// 绘制二维码到背景图上const qrImage = textCanvas.createImage();qrImage.src = tempQrcodePath;qrImage.onload = () => {textCtx.drawImage(qrImage, qrX, qrY, qrWidth, qrHeight);// 合成图像成功后隐藏二维码this.setData({qrcodeVisible: false});};qrImage.onerror = () => {console.error('二维码绘制失败');};},// 长按保存// 最终合成图像保存到临时路径saveQrcode() {wx.getSetting({success: (res) => {if (!res.authSetting['scope.writePhotosAlbum']) {wx.authorize({scope: 'scope.writePhotosAlbum',success: () => {this.saveCanvasToAlbum();},fail: (err) => {console.error('用户拒绝授权保存相册', err);wx.showToast({title: '未授权保存相册',icon: 'none'});}});} else {this.saveCanvasToAlbum();}}});},saveCanvasToAlbum() {wx.showLoading({title: '正在保存图片...',});wx.canvasToTempFilePath({canvas: textCanvas,success: (finalRes) => {wx.saveImageToPhotosAlbum({filePath: finalRes.tempFilePath,success: () => {wx.hideLoading();wx.showToast({title: '保存成功',});},fail: (err) => {wx.hideLoading();console.error('保存失败', err);wx.showToast({title: '保存失败',icon: 'none'});},});},fail: (err) => {wx.hideLoading();console.error('合成图像失败', err);wx.showToast({title: '合成图像失败',icon: 'none'});},});}
});

引入文件

http://www.lryc.cn/news/543250.html

相关文章:

  • 轻量化网络设计|ShuffleNet:深度学习中的轻量化革命
  • 一天记20个忘10个之五:land
  • Python 类(创建和使用类)
  • LeetCode 解题思路 3(Hot 100)
  • 算法-二叉树篇11-左叶子之和
  • MaxKB上架至阿里云轻量应用服务器镜像市场
  • 用户态和内核态是什么?
  • 2025年SCI一区智能优化算法:混沌进化优化算法(Chaotic Evolution Optimization, CEO),提供MATLAB代码
  • 普中单片机-51TFT-LCD显示屏(1.8寸 STM32)
  • SGMII(Serial Gigabit Media Independent Interface)详解
  • DeepSeek:我的AI助手之旅
  • 图片批量去重---(均值哈希、插值哈希、感知哈希、三/单通道直方图)
  • Linux:(3)
  • vscode设置自动换行
  • Instagram 隐私设置全面解析:如何保护你的个人数据?
  • Activiti 5 + Spring Boot全流程开发指南
  • spring结合mybatis多租户实现单库分表
  • 面向对象编程(OOP)基础:Java入门指南
  • day7作业
  • 图像处理之图像边缘检测算法
  • 第二十五 :搭建 pinia 环境
  • 学习Java数组操作:从基础到高级技巧详解
  • 算法题(79):两个数组的交集
  • TFChat:腾讯大模型知识引擎+飞书机器人实现AI智能助手
  • Linux红帽:RHCSA认证知识讲解(四)修改远程配置文件,取消root禁用,便于使用root身份远程
  • 验证码介绍及生成与验证(HTML + JavaScript实现)
  • 文心一言AI创意画
  • WebRTC解析
  • 升级Office软件后,Windows 系统右键里没有新建Word、Excel、PowerPoint文件的解决办法
  • 车载DoIP诊断框架 --- 连接 DoIP ECU/车辆的故障排除