当前位置:Gxlcms > JavaScript > 微信小程序实现的canvas合成图片功能示例

微信小程序实现的canvas合成图片功能示例

时间:2021-07-01 10:21:17 帮助过:3人阅读

本文实例讲述了微信小程序实现的canvas合成图片功能。分享给大家供大家参考,具体如下:

先要获取图片的信息  然后将需要合成的内容用canvas绘制出来,得到一个合成好的画布,接下来用 wx.canvasToTempFilePath 把当前画布指定区域的内容导出生成指定大小的图片,并返回文件路径。这个时候的路径 是微信的临时路径,浏览器是访问不了的,因此需要请求服务器  用 wx.uploadFile 将本地资源上传到开发者服务器。

在页面的wxml中加入canvas组件如下:

<view class="canvasBox">
 <canvas canvas-id="shareCanvas" style="width:375px;height:300px"></canvas>
</view>

在js中

picture: function () { //生成图片
   let that = this;
   let p1 = new Promise(function (resolve, reject) {
    wx.getImageInfo({
     src: 图片路径,
     success(res) {
      resolve(res);
     }
    })
   }).then(res => {
    const ctx = wx.createCanvasContext('shareCanvas');
    ctx.drawImage(res.path, 0, 0, 375, 300);  //绘制背景图
    //ctx.setTextAlign('center')  // 文字居中
    ctx.setFillStyle('#000000') // 文字颜色:黑色
    ctx.setFontSize(20)     // 文字字号:22px
    ctx.fillText("文本内容", 20, 70) //开始绘制文本的 x/y 坐标位置(相对于画布) 
    ctx.stroke();//stroke() 方法会实际地绘制出通过 moveTo() 和 lineTo() 方法定义的路径。默认颜色是黑色
    ctx.draw(false, that.drawPicture());//draw()的回调函数 
    console.log(res.path);
   })
  },
  drawPicture: function () { //生成图片
    var that = this;
   setTimeout(function(){
    wx.canvasToTempFilePath({ //把当前画布指定区域的内容导出生成指定大小的图片,并返回文件路径
     x: 0,
     y: 0,
     width: 375,
     height: 300,
     destWidth: 750, //
输出的图片的宽度(写成width的两倍,生成的图片则更清晰) destHeight: 600, canvasId: 'shareCanvas', success: function (res) { console.log(res); that.draw_uploadFile(res); }, }) },300) }, draw_uploadFile: function (r) { //wx.uploadFile 将本地资源上传到开发者服务器 let that = this; wx.uploadFile({ url: 图片上传接口, //线上接口 filePath: r.tempFilePath, name: 'imgFile', success: function (res) { console.log(res); if(res.statusCode==200){ res.data = JSON.parse(res.data); let imgsrc = res.data.data.src; that.setData({ imgPath: imgsrc }); }else{ console.log('失败') } }, }) },

注意:若是将此方法写成自定义组件,则 wx.createCanvasContextwx.canvasToTempFilePath 都需要多传一个this

因在自定义组件下,当前组件实例的this,用以操作组件内 <canvas/> 组件。

至于分享的话 ,拿到服务器返回的图片路径之后 就可以用来写分享的图片路径了

希望本文所述对大家微信小程序开发有所帮助。

人气教程排行