WeChat applet-canvas draw pictures

Since the applet cannot be shared to the circle of friends, if we want to share to the circle of friends, we can only generate one poster.

At this time, we will use canvas to draw pictures

First, create a canvas container

// 展示图片,并保存到本地
<view class='imagePathBox' v-if="showPoster"> <image v-if="imagePath" :src="imagePath" class='shengcheng'></image> <view v-if="imagePath == ''" class="poster_ing">海报生成中...</view> <view class='baocun' @tap='baocun'>保存相册,分享到朋友圈</view> <image src="/static/icon_oc_close.png" class="post_close" @tap="closePoster"></image> </view>
// canvas容器 <view class="canvas-box"> <canvas style="width: 375px;height: 667px;position:fixed;top:9999px" canvas-id="mycanvas" /> </view>

Second, the server obtains the QR code of the applet

Why is it that the server obtains the applet code, because the WeChat public platform does not allow  binding the  https://api.weixin.qq.com domain name to the service request whitelist

getCode: function () { 
  let that = this 
  let channelId = compress (app.globalData.channelId) 
  let custId = compress ( this .custInfo.custId) 
  let customId = compress (that.customId) 
  let str = channelId + '/' + custId + '/' + customId 
 // Here we need to explain that the scene is a parameter followed by the page, and the effective length is 32 bits, and it cannot be coded if it exceeds, so be sure to control the length
// because the parameter I want to pass is just right It is a pure number, so my method is to convert the original decimal to 32 hexadecimal, and then convert it when taking the parameters.
// Of course, if the amount of data required is relatively large, you can also save the data to the background, only
 Just pass the id and get the accessToken. You can see the API uni.request ({ url:
'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' +this .accessToken, data: { scene: str, page: "pages / personal / routerSharePage / routerSharePage" }, method: "POST" , responseType: 'arraybuffer', // Set response type success (res) {
    // Convert to base64 bit
var codeSrc = uni.arrayBufferToBase64 (res.data); // Convert data to that.setData ({ codeSrc: codeSrc }) that.createNewImg () }, fail (e) { console.log (e) } }) },

Three, draw canvas

createNewImg: function () {
   var that = this ; 
 // Because base64 cannot directly generate an image, it needs to be converted to a local image let pathCode
= "data: image / png; base64," + this .codeSrc const fsm = wx.getFileSystemManager ( ); const FILE_BASE_NAME = 'tmp_base64src' ; const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(pathCode) || [] const filePath = `$ { wx.env.USER_DATA_PATH} / $ {FILE_BASE_NAME}. $ {format} `; const buffer = wx.base64ToArrayBuffer (bodyData); fsm.writeFileSync (filePath, buffer, 'binary' )
/ *Create container * / var context = uni.createCanvasContext ('mycanvas' ); / * Main background color * / context.setFillStyle ( "#ffffff" ) / * Background color fill area * / context.fillRect ( 0, 0, 375, 667 ) // Draw the template picture to the canvas, there is a problem with the drawImage () function in the development tool, the picture is not displayed context.drawImage ( this .headerImg, 0, 0, 375, 421 ); / * Draw slogan * / let text1 = 'My line is my choice' let text2 = 'I am a line partner, help me' context.setFontSize ( 24 ) context.setFillStyle ( "# 181818" ) context.setTextAlign('center') context.fillText(text1, 185, 467) context.stroke() context.setFontSize(18) context.setFillStyle("#4D4D4D") context.setTextAlign('center') context.fillText(text2, 185, 500) context.stroke() /* 画虚线 */ context.lineWidth = 3 context.strokeStyle = "#4D4D4D" context.beginPath() context.setLineDash([18.5, 4]) context.moveTo(37.5, 525) context.lineTo(337.5, 525 ) context.stroke () / * applet QR code * / context.drawImage (filePath , 41, 547, 82, 82 ); / * applet description * / let text3 = 'Share from Beijing customized bus upgrade Version ' let text4 =' Long press recognition applet to participate immediately ' context.setFontSize ( 15 ) context.setFillStyle ( "# 181818" ) context.setTextAlign ( ' left ' ) context.fillText (text3, 140, 579 ) context.stroke () context.setFontSize ( 14 ) context.setFillStyle ( "# 4D4D4D" ) context.setTextAlign ('left' ) context.fillText (text4, 140, 610 ) context.stroke () context.draw (); // Save the generated picture to the local, need to delay for a while, it takes time during drawing setTimeout ( function () { uni.canvasToTempFilePath ({ canvasId: 'mycanvas' , success: function (res) {    var tempFilePath = res.tempFilePath; uni.hideLoading () that.setData ({ imagePath: tempFilePath, showPoster: true }); }, fail: function (res) { console.log(res); } }); }, 200);
},

Fourth, save the picture

baocun: function () { 
   uni.showLoading ({ 
      title: 'Downloading' , 
   }) 
   if ( this .imagePath.indexOf ('https')> -1) {} else {
       this .imagePath = this .imagePath.replace ( 'http', 'https' ) 
    } 
    uni.saveImageToPhotosAlbum ({ 
       filePath: this .imagePath, 
       success (res) { 
         uni.showModal ({ 
            content: ' The picture has been saved to the album, hurry up ~~ , 
            showCancel: false , 
            confirmText: 'OK',
            confirmColor: '#333',
            success: function(res) {
              if (res.confirm) {
                 uni.hideLoading()
              }
            },
            fail: function(res) {
               console.log(11111)
            }
         })
       }
    })
  },

ok, that ’s all, if you have any questions, you can leave a message

Guess you like

Origin www.cnblogs.com/WQLong/p/12746379.html