欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-10-28 21:06:04
本文实例讲述了微信小程序实现的canvas合成图片功能。分享给大家供大家参考,具体如下: 先要获取图片的信息  然后将需要合成的内容用canvas绘制出来,得到...

本文实例讲述了微信小程序实现的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

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

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

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

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