1.图片绘制到canvas
<canvas type="2d" id="canvas"></canvas> <view catchtap="canvasSave">保存到相册</view>
onLoad: function (options) { wx.createSelectorQuery() .select('#canvas') .fields({ node: true, size: true, }) .exec(this.drawInit.bind(this)) }, drawInit: function (res) { const width = res[0].width const height = res[0].height const canvas = res[0].node const ctx = canvas.getContext('2d') const dpr = wx.getSystemInfoSync().pixelRatio const canvasWidth = width * dpr const canvasHeight = height * dpr canvas.width = canvasWidth canvas.height = canvasHeight ctx.scale(dpr, dpr) this.data.canvas = canvas this.data.ctx = ctx this.data.canvasWidth = canvasWidth this.data.canvasHeight = canvasHeight this.data.dpr = dpr }, getData:function () { //异步接口获取数据,回掉函数中调用draw,这里的setTimeout很关键,开发工具中不加也正常,一旦真机执行就会报错 setTimeout(()=>{ this.draw(res.data[0]) },1000) } draw: function (product) { var canvas = this.data.canvas var ctx = this.data.ctx var canvasWidth = this.data.canvasWidth var canvasHeight = this.data.canvasHeight var dpr = this.data.dpr var url = product.url[0] var title = product.title //白色背景 ctx.fillStyle="#FFFFFF"; ctx.fillRect(0,0,canvasWidth,canvasHeight) ctx.fillStyle="#000000" ctx.fillText(title, 20, canvasHeight/dpr/2+20) //因为使用云开发,用云文件 ID 换取真实链接 wx.cloud.getTempFileURL({ fileList: [url], success: res => { var imgUrl = res.fileList[0].tempFileURL const img = canvas.createImage() img.onload = (res) => { ctx.drawImage(img, 0, 0, canvasWidth/dpr, canvasHeight/dpr/2) } img.src = imgUrl } }) }
流程:
onload阶段进行canvas的初始化
远程接口获取数据,获取到图片后进行渲染
注意setTimeout如果不加手机上测试会报错
2.将canvas内容生成图片并保存
canvasSave: function () { var _this = this var canvasWidth = this.data.canvasWidth var canvasHeight = this.data.canvasHeight var dpr = this.data.dpr wx.canvasToTempFilePath({ x: 0, y: 0, width: canvasWidth, height: canvasHeight, destWidth: canvasWidth*dpr, destHeight: canvasHeight*dpr, canvas: this.data.canvas, //注意此参数 success: res => { wx.saveImageToPhotosAlbum({ filePath:res.tempFilePath, success(res) { wx.showToast({ icon:'success', title:'保存成功!' }) } }) } }) }
注意文档中canvasId和canvas两个参数的不同传值
保存图片前,要进行权限检查
3.ActionSheet中如何添加分享button
<action-sheet hidden="{{actionSheetHidden}}" bindchange="listenerActionSheet"> <action-sheet-item>分享</action-sheet-item> <action-sheet-cancel>取消</action-sheet-cancel> </action-sheet>
原生ActionSheet中结构固定,不能添加别的元素进去,其实基于功能而言,完全可以自己重写一个,但是它的一些元素是可以复用的,基于ui交互体验的一致性,代码可维护性,我们在原生组件上进行局部修改
保留action-sheet组件可以获得原生蒙版效果,内部元素都可删除
4.弹出层蒙版,在点击透明区域时候隐藏
<view class="mask" bindtap="hideMask"> <view catchtap="stopBubbling"></view> </view>
stopBubbling: function () { //内容为空,确保函数存在,目的阻止蒙版内部事件传播 }
内部元素用了catchtap