本篇文章给大家介绍一下在微信小程序中使用canvas+painter插件制作二维码的方法,希望对大家有所帮助!
在日常的小程序项目中,会经常遇到需要动态绘制二维码的需求。使用场景很多,例如绘制在海报上,例如制作票务码、核销码等等。
这篇文章是应一位好友的需求而写的,也希望能够给有需要的同学一些帮助。
一、实现原理使用微信小程序的canvas组件进行绘制,但是在该组件用起来并不是很顺手,所以使用了第三方的框架:painter
painter的github地址:https://github.com/kujiale-mobile/painter
用你的方法,把这个框架下载下来,里面会有示范代码,我们只需要把其中的核心代码拿出来就行。
对于框架的使用介绍,大家可以前往github浏览,我这就直接上手了。【相关学习推荐:小程序开发教程】
二、实现代码前期准备
1、新建components文件夹,放置painter核心代码
2、新建palette文件夹,放置绘制实现代码
painter.js代码
export default class lastmayday { palette(viewlist) { return ( viewlist ); }}
3、新建绘制的具体属性信息文件夹posterviewjs,放置例如绘制的大小、位置等信息js。
二维码绘制属性信息js代码
const getposterview01 = (qrcodetext) => { const poster01 = { width: 256px, height: 256px, background: #f8f8f8, views: [{ type: qrcode, content: qrcodetext, css: { color: #000000, background: #ffffff, width: 256px, height: 256px, top: 0px, left: 0px, rotate: 0, borderradius: 0px } }] } return poster01}module.exports = { getposterview01: getposterview01}
实现
实现页面目录结构
wxml代码
<view class="flex-jc-ac-col" style="margin-top: 200rpx;"> <image class="qrcode-img" src="{{imgurl?imgurl:''}}" mode="widthfix"></image> <button type="primary" style="margin-top: 105rpx;" bindtap="makeqrcodetap">生成二维码</button></view><!-- canvas隐藏 --><painter customstyle='position: absolute; left: -9999rpx;' customactionstyle="{{customactionstyle}}" dancepalette="{{template}}" palette="{{paintpallette}}" bind:imgok="onimgok" bind:touchend="touchend" action="{{action}}" use2d="{{true}}" widthpixels="720" /><!-- canvas隐藏 -->
wxss代码
.qrcode-img{ background-color: #999999; height: 300rpx; width: 300rpx;}
json代码
注意记得在使用的页面引用painter组件
{ usingcomponents: { painter:/components/painter/painter }, navigationbartitletext: 绘制二维码}
js代码
// pages/makeqrcode/makeqrcode.jsimport poster from '../../palette/painter'const posterview = require(../../posterviewjs/posterview)page({ /** * 页面的初始数据 */ data: { imgurl: null, qrcodetext: 2d44d6c26134f8a109df65897107089a2d44d6c26134f8a109df65897107089a, paintpallette: '', }, /** * 生命周期函数--监听页面加载 */ onload() { }, /** * 生命周期函数--监听页面显示 */ onshow () { }, /** 生成海报点击监听 */ makeqrcodetap() { wx.showloading({ title: '获取海报中', mask: true }) // 绘制海报 this.makeposter(this.data.qrcodetext) }, /** 绘制完成后的回调函数*/ onimgok(res) { wx.hideloading() // 这个路径就可以作为保存图片时的资源路径 // console.log(海报临时路径, res.detail.path) this.setdata({ imgurl: res.detail.path }) }, /** 生成海报 */ makeposter(qrcodetext) { wx.showloading({ title: '生成海报中', }) // 这是绘制海报所用到json数据 const viewlist = posterview.getposterview01(qrcodetext) this.setdata({ paintpallette: new poster().palette(viewlist) }) }, /** * 用户点击右上角分享 */ onshareappmessage() {}})
实现效果
三、结语实际开发中的其他逻辑就不写了。需要同学们自己去考虑异常情况处理等问题啦。
以上均是本人开发过程中的一些经验总结与领悟,如果有什么不正确的地方,希望大佬们评论区斧正。
本文转载自:https://blog.csdn.net/weixin_44702572/article/details/120443998
作者:super--yang
更多编程相关知识,请访问:编程入门!!
以上就是手把手教你在微信小程序中使用canvas+painter插件制作二维码的详细内容。
