900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 在微信小程序中实现生成海报图并保存到相册

在微信小程序中实现生成海报图并保存到相册

时间:2021-02-10 13:37:50

相关推荐

在微信小程序中实现生成海报图并保存到相册

效果图镇楼:

技术依赖:

弹窗 (vant-weapp 提供的 van-popup 组件)海报图 (wx-canvas-2d 工具)

弹窗组件的使用方式可以点击上面链接查看,本篇主要讲解海报图绘制方法。

首先下载依赖

npm install -S wx-canvas-2d

下载完依赖后也不要忘记用微信开发者工具构建一下npm。

使用wx-canvas-2d前,先要准备一个容器,请在需要绘制海报图的地方创建一个canvas,如下:

<canvastype="2d"id="poster-canvas"class="poster-canvas"style="width: 100%; height: 100%;"disable-scroll="{{ true }}"/>

接下来就可以开始编写js代码部分了。第一步,先引入,然后实例化对象。

import WxCanvas2d from 'wx-canvas-2d'// 实例化对象const canvas = new WxCanvas2d()

第二步,在canvas加载完毕后创建画布

// 创建canvas.create({query: '.poster-canvas', // 必传,canvas元素的查询条件rootWidth: 750, // 参考设备宽度 (即开发时UI设计稿的宽度,默认375,可改为750)bgColor: '#fff', // 背景色,默认透明component: this, // 自定义组件内需要传 thisradius: 16 // 海报图圆角,如果不需要可不填}).then(res => {// console.log(res)}).catch(err => {console.log('[WxCanvas2d] Canvas create fail: ', err)})

设置了rootWidth后,接下来绘制内容时填入的数值就直接是设计图上的实际值了。

最后一步,绘制内容,在你需要绘制的地方调用绘制方法draw

// 绘制canvas.draw({series: [{type: 'image', // 图片url: item.img,x: 0,y: 0,width: 600,height: 600,mode: 'aspectFill' // 图片的裁剪方式,参考小程序 image 标签的 mode 属性},{type: 'text',text: item.name,x: 30,y: 620,color: '#222',fontSize: 30,fontWeight: 'bold',lineHeight: 42},{type: 'text',text: '¥',x: 30,y: 683,color: '#F25238',fontSize: 24,fontWeight: 'bold',lineHeight: 33},{type: 'text',text: item.price,x: 49,y: 672,color: '#F25238',fontSize: 34,fontWeight: 'bold',lineHeight: 48},{type: 'text',text: item.desc,x: 30,y: 787,color: '#969696',fontSize: 24,width: 390,lineHeight: 33,ellipsis: 2},{type: 'line',lineStyle: {dash: [7, 3],color: '#E9E9E9',width: 1},line: [{point: [30, 740]},{point: [30 + 540, 740]}]},{type: 'image',url: '../../img/qrcode.png',x: 450,y: 760,width: 120,height: 120}]}).then(() => {console.log('绘制成功!')}).catch(err => {console.log('绘制失败!', err)})

type属性是必填的,zIndex属性可有可无。

基本上可以做到海报图需要的大多数功能了,绘制图片,绘制线段,绘制文字,文字换行,文字超出省略号,绘制矩形。

选择这个工具的优势主要在于其满足了绝大部分海报图所需的功能,而且非常小巧,使用方便,容易维护,对于有 2MB 限制的小程序来说,工具的体积大小是非常重要的一个指标。

除此以外,wx-canvas-2d工具还十分人性化的集成了保存图片到相册的功能。

// 保存图片到相册canvas.saveToAlbum({destWidth: 600,destHeight: 900}).then(res => {wx.showModal({content: '图片已保存到相册,赶紧晒一下吧~'})}).catch(err => {wx.showModal({content: '图片保存失败'})})

看完有收获的点个赞再走~

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。