Project address: github.com/yancekang/w… Welcome to star

Presentation:

Unlike the client, the poster generation by applet can not be taken from the specified part of the page as the poster generation, but needs to use canvas to generate a picture according to the poster template.

First let’s look at the implementation

First we need to insert the canvas tag on the page

To hide the canvas through CSS, you need to position the canvas in the invisible part of the page. Set the following properties to position the canvas outside the page.

 position: fixed;
 left: -200vw;
Copy the code

Note: The canvas size is set to use PX as far as possible, in order to make the size consistent with the generated poster size

You cannot hide the canvas with display: None

Began to draw

Create the Canvas drawing object wx.createcanvasContext

 letCanvasW = 700 // Define the canvas width and height according to the poster template definitionlet canvasH = 1200 
 const ctx = wx.createCanvasContext('my_canvas'Ctx.clearrect (0, 0, canvasW, canvasH) // Clear the canvas ctx.setFillstyle ('#ffffff'// Set the fill color ctx.fillrect (0, 0, canvasW, canvasH) // to fill the canvasCopy the code

After that, the canvas is a whiteboard with a 700 x 1200 white background.

Start by drawing a blue background at 800px height

// Draw a blue background ctx.setfillstyle ('#0B5FA5'// Set the fill color ctx.fillrect (0, 0, 690, 800)Copy the code

Draw the word of the day, where the length of the text is calculated and the content is centered above and below the blue area

ctx.setFontSize(40); // Set the font size ctx.setfillstyle ("#fff") // Set the font colorCopy the code

Wrap lines according to the length of the content. When each line exceeds 630, enter the second line to draw. Here, put each line of text into an array, and then draw the data in the array.

for (var a = 0; a < yiyu.length; a++) {
	if(ctx.measureText(temp).width < 630 && ctx.measureText(temp + (yiyu[a])).width <= 630) { temp += yiyu[a]; }//ctx.measureText(text).width Measures the width of text textelse {
    	row.push(temp);
    	temp = yiyu[a];
    }
}
row.push(temp);
Copy the code
// Find the Y coordinate of the drawing content, that is, the height of the blue area - content height (number of lines x line height) / 2let top = (800 - row.length * 48) / 2
for (var b = 0; b < row.length; b++) {
	console.log(((800 - top) / 2) + (b + 1) * 48)
	ctx.fillText(row[b], 30, top + (b + 1) * 48);
}
Copy the code

At this point, the blue area and content are drawn

Next draw the user’s nickname and avatar, two-dimensional code, the next is relatively simple, a layer by layer to draw on the line.

When drawing an image, it is worth noting that the image needs to be converted to a local image first

The image resource to draw (web images can be downloaded via getImageInfo/downloadFile)

Drawing picture

// 45 is rounded and 90 is the width and height of the head
ctx.save()
ctx.arc(30 + 45.855 + 45.45.0.2 * Math.PI);
ctx.clip()   // Cut rounded corners
ctx.drawImage(this.data.user_img, 30.855.90.90)
ctx.restore()  // Restore the last save
Copy the code

Draw nicknames and prompts

// Draw the nickname ctx.setfontSize (32); ctx.setFillStyle("# 333")
ctx.fillText('Tech guy', 150, 890)
ctx.setFontSize(24);
ctx.setFillStyle("# 999")
ctx.fillText('Invite you to use wechat applet', 150, 930)
Copy the code

Draw two-dimensional code

DrawImage (this.data.qr_img, 540, 835, 100, 100) ctx.filltext ('Long press to identify qr code', 500, 970)
Copy the code

At this point, the entire poster is completed.

To save to album, you need to obtain album permission

wx.getSetting({
	success(res) {
        if(! res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
                scope: 'scope.writePhotosAlbum'.success() {
                    that.saveImages()
                },
                fail() {
                    wx.showToast({
                        title: 'Save failed',
                        icon: "none"})}})}else {
            that.saveImages()
            }
    	}
    })
})
Copy the code

Generate and save the canvas image

wx.canvasToTempFilePath({
      canvasId: 'my_canvas',
      success(res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) {
            wx.hideLoading()
            wx.showToast({
              title: 'Saved successfully',
              icon: 'none'
            })
          }, complete: function () {
            wx.hideLoading()
          }
        })
      }
    })
Copy the code