Wechat applet generating Poster Canvas text wrapping

Time:2020-4-2

Sharing in wechat applets, the official website only provides the ability to share to friends and group chat, not the API to share to the circle of friends. Therefore, the common way to share the applet to the circle of friends is to generate a dynamic poster with canvas, paste a picture of the applet code on it, share it to the circle of friends, press and hold the identification applet code to enter the applet, so as to achieve the function of promoting the applet in the circle of friends.

The following problems are mainly encountered in the actual project development:

  1. word wrap
  2. Poster highly adaptive, dynamically set according to poster content
  3. Draw network pictures
  4. Authorized to save pictures to mobile phone

Step on all the above pits and summarize the solutions to the above problems:

Initialize canvas

1. Create a canvas in. Wxml,canvasWidthandcanvasWidthThey are the width and height of the canvas created.
For example, the poster size we need to save is 750px * 1350px; we can set canvas width = 750; canvas width = 1350; the resulting image is relatively clear.

<view class="canvas-box">
    <canvas canvas-id="canvas" class="canvas" style="width: {{canvasWidth}}px; height: {{canvasHeight}}px;"></canvas>
<view>

2. The canvas level is the highest in the applet. So we need to hide canvas from the window.

.canvas-box{  
  position: fixed;  
  top: 1000px;  
  left: 1000px;  
  z-index: -10;  
}
  1. Get canvas context in JS
const ctx = wx.createCanvasContext('canvas'); // canvas-id

Draw pictures

The API for small programs to draw pictures is relatively simple. Generally, the following methods can be used directly

const img = '/assets/images/bg.png';
Const imgx = 0; // draw the starting point X coordinate of the picture in canvas
Const imgy = 0; // draw the starting y coordinate of the picture in canvas
Const imgwidth = 0; // draw the width of the picture in canvas
Const imgheight = 0; // draw image height in canvas
ctx.drawImage(img, imgX, imgY, canvasWidth, canvasHeight);

Local image

Applet drawing local pictures can be used directly, such as the above/assets/images/bg.png'You can draw directly on canvas.

Network picture

The applet can’t directly draw network pictures into canvas.
1. Need to passwx.getImageInfoGet picture information orwx.downloadFileDownload to local.
2. Get picture information. The download domain name must be configured for the network picture to take effect. If you need to draw wechat user’s Avatar, you also need to add Tencent’s domain name to the white list.

In this case, wx.getimageinfo is used to request all network pictures that need to be drawn to canvas during page initialization

Const localimginfo = {}; // stores all network pictures requested to local objects
const imgList = [  
  img1,
  avatar,
];  
imgList.forEach((item, index) => {  
  wx.getImageInfo({  
    src: item,  
  success: function (res) {  
      //Save to local array  
  localImgInfo[item] = res.path;  
  }  
  })  
})

... (make sure the network picture is loaded) draw the network picture

ctx.drawImage(localImgInfo[avatar], imgX, imgY, canvasWidth, canvasHeight);

Draw text

Ctx.setfontsize (30); // text font size
CTX. Setfillstyle ("ාe1e6f0"); // color
Const text = 'I am text';
const textX = 0;  
const textY = 0;

ctx.fillText(text, textStartX, textY);

There is a cell for drawing text and pictures. Don’t notice that the starting X and Y coordinates are inconsistent.
The X and Y coordinates of a picture are drawn from the pictureTop left cornerStarting to calculate the location.
Draw the X and Y coordinates of the text from the textLower right cornerStarting to calculate the location.

word wrap

ctx.measureText()The width of the text in canvas can be obtained, and the text can be wrapped manually by this method

//Draw text to President text wrap and return the number of lines  
/\*  
\* params  
\*@ text text characters to draw  
\*@ startx start X coordinate of the first line of text  
\*@ startycoordinate of the first line of text  
\*@ lineheight text line height  
\*@ Max \ \  
\*  
\*Return rowlength returns the number of lines of drawn text  
\* \*/
function drawText(text, startX, startY, lineHeight, MAX\_WIDTH) {  
  let allAtr \= text.split('');  
  Let rowarrow \ = \ [\]; // split each row  
  Let rowstrarr \ = \ [\]; // text array of each line  
  for (let i \= 0; i < allAtr.length; i++) {  
    const currentStr \= allAtr\[i\];  
  rowStrArr.push(currentStr);  
  const rowStr \= rowStrArr.join('');  
  if (ctx.measureText(rowStr).width \> MAX\_WIDTH) {  
      Rowstrarr. Pop(); // delete the last  
  Rowarrow. Push (rowstrarr. Join (''); // complete a line  
  rowStrArr \= \[currentStr\];  
  continue;  
  }  
    //The last letter is added directly to a line  
  if (i \=== allAtr.length \- 1) {  
      Rowarrow. Push (rowstr); // complete a line  
  }  
  }  
  
  for (let i \= 0; i < rowArr.length; i++) {  
    ctx.fillText(rowArr\[i\], startX, startY \+ i \* lineHeight);  
  }  
  return rowArr.length;  
}

drawText()The main function of the function is to draw the incoming text using thectx.measureText()Determine whether the width of single line text exceeds the maximum width of single line. If it exceeds the width, set the start y coordinate of CTX drawn text to the current start y + text line height to achieve the effect of switching to the next line

Canvas height dynamic setting

Because the height of the poster image generated in the project changes with the content, resulting in the height of the poster generated by different content is inconsistent, so we only need to put the height of canvas in data, then calculate the height of the final poster dynamically according to different content, and then set the height of canvas in data immediately.

Here is the actual effect of the project. Here, the poster consists of three parts: the head, the content and the bottom. The height of the head and the bottom is fixed, and the height of the middle content is determined by the number of books returned from the background, among which the title and subtitle of the book may need to be wrapped.

Wechat applet generating Poster Canvas text wrapping

Here we simply treat each book as an area with a fixed height, soHeight of content area = number of books * height of booksThrough this method, the height of the middle content area is simply calculated, and then the height of canvas is set dynamically.

Source code

https://github.com/zhaosheng808/canvasPoster

A simple wechat applet test number demo is provided, which contains the authorization logic for requesting users to save canvas pictures.

The test number needs to open the illegal domain name, otherwise the wechat avatar and external picture cannot be displayed. Official number needs to be configured in wechat public platform to download domain name

Wechat applet generating Poster Canvas text wrapping

Recommended Today

Rolling upgrade scheme of kakfa cluster (2.11-0.10.1.0)

  Kafka cluster version upgrade (2.11-0.10.1.0) upgrade (2.11-0.10.2.2) Official website upgrade instructions:   1、 System environmentZookeeper cluster:172.16.2.10172.16.2.11172.16.2.12Kafka cluster:172.16.2.10172.16.2.11172.16.2.12 Current Kafka version: 2.11-0.10.1.0, installation directory: usr / local / KafkaPlan to upgrade to version: 2.11-0.10.2.2, installation directory: usr / local / Kafka_ 2.11-0.10.2.2 2、 Create test topic1. Create test topic /usr/local/kafka/bin/kafka-topics.sh –zookeeper 172.16.2.10:2181,172.16.2.11:2181,172.16.2.12:2181 –create –replication-factor 3 […]