I just finished a wechat mini program project, and now I am sorting out some functions of the project. This article records how to realize the generation of posters with TWO-DIMENSIONAL code in the mini program and save them in the user album.

This article is recorded for use in subsequent projects.

The project is based on MPVUE.

Project requirement

Each user can generate a promotion of their own TWO-DIMENSIONAL code, after the new record promoter.

The final effect of the generated poster is not complicated, as shown in the figure:

Demand analysis

According to the documents of wechat mini program, we can draw a Canvas map according to the design drawing by virtue of the canvas drawing function provided by the mini program, and then save the picture to the album of the user’s mobile phone through the API of saving picture to album.

Posters of some of the content is fixed, such as background, invitation and long according to the clues of the picture below, and also some content is dynamic, such as a user name and small program code, different project requirements is different, but there will be changes and the same two types of content, and then we according to the design point is plotted on a graph the content.

Now that we know what we need to do, let’s make a list of what we need to do. (The Gidlin rule goes like this: List the problems we need to solve clearly, and the problems are half solved.)

  • Obtaining a user name
  • Get user – specific applets
  • Image rendering
  • Handles user unauthorization to save to album

implement

  1. First, insert a Canvas tag into the page and move its position outside the interface. As for why it is by controlling the position instead of controlling the show and hide, anyone who has tried it should know that it is a matter of priority.
<canvas class="cv-ct-canvas" canvas-id="cv-pic"></canvas>

.cv-ct-canvas {
  position: absolute;
  left: 800rpx;
  width: 300px;
  height: 500px;
}
Copy the code
  1. Prepare the user name and applets. Since the background image I have here is also a remote image, I also need to download it first.
const { tempFilePath: bg } = await this.downloadFile('$(STATICFILE_URL)/prom-share-bg.png')
letname = this.userInfo.NickName; Const {tempFilePath} = await this.downloadFile(this.qrcodeurl);Copy the code

It should be noted that this downloadFile method synchronizes wechat’s downloadFile method. In fact, it is very simple, just wrapped with a Promise.

  1. I’m going to draw one by one on the canvas.
const ctx = wx.createCanvasContext("cv-pic");
// Fill the background color
ctx.setFillStyle("#f8f8f8");
ctx.fillRect(0.0.300.400);
ctx.fill();
ctx.setFillStyle("#ffffff");
ctx.fillRect(0.400.300.100);
ctx.fill();
// Fill the background image
ctx.drawImage(bg, 30.20.240.365);
// Write the name
ctx.setFontSize(15);
ctx.setFillStyle("#FFF9F0");
ctx.fillText(name, 61.300);
// Write two lines of prompts
ctx.setFillStyle("#322F30");
ctx.setFontSize(14);
ctx.fillText("Long press to identify small code".33.440);
ctx.fillText("Great value bag for you to grab.".33.465);
// Fill in the small program code
ctx.drawImage(tempFilePath, 0.0.280.280.200.410.80.80);
const that = this;
// Save the Canvas map to a temporary directory
ctx.draw(false.function() {
  wx.canvasToTempFilePath({
    canvasId: "cv-pic",
    success(res) {
      leturl = res.tempFilePath; that.savePic = url; }}); });Copy the code

In the end, I saved the Image to the temporary directory with canvasToTempFilePath, and assigned the address of the temporary directory to savePic. Because the Image is displayed on the interface, there will be an Image tag on the interface, and the address of the tag is savePic.

  1. Save to the user album, the code is relatively simple, directly on:
if (!this.savePic) return;
  const that = this;
  wx.saveImageToPhotosAlbum({
    filePath: this.savePic,
    success: function() {
      that.showSaveCode = false;
      wx.showToast({
        title: "Saved successfully".icon: "success".duration: 2000
      });
    },
    fail: function () {
      that.getWriteToAlbumSetting()
    }
  });
Copy the code

The getWriteToAlbumSetting method in this last fail is explained below.

  1. Handle user denial of authorization. For operations that require user authorization, we now do this:
  • First declare a variable in the page data to indicate whether the current user is authorized. For example, HERE I declare canWriteToAlbum to indicate whether images can be saved to the album.
  • Mounted hook (getWriteToAlbumSetting); mounted hook (getWriteToAlbumSetting); mounted hook (wx.getSetting);
async getWriteToAlbumSetting() {
  The this.getSetting method is also a synchronous wrapper around wx.getSetting
  let status = await this.getSetting('writePhotosAlbum')
  // The authorization status is undefined when the user performs the operation for the first time. The authorization status is false only when the user explicitly rejects the operation
  if (status === true || status === undefined) {
    this.canWriteToAlbum = true
  } else {
    this.canWriteToAlbum = false}}Copy the code
  • In the page, according to the user’s authorization, the same surface but different operation buttons are displayed:
<div class="cv-save" @click="saveToPhotosAlbum" v-if="canWriteToAlbum"> Save the picture </div> <div class="cv-save" @click="openAlbumSetting"V-else > Save image </div>Copy the code

As for why to do this, of course, because of the limitations of the small program. If the user refuses authorization and clicks the save button again, the authorization interface will pop up. However, wechat clearly requires that the popup authorization interface must be triggered by the user directly clicking the button, so it can only be realized in this way. OpenAlbumSetting code is as follows:

async openAlbumSetting() {
  // Or the wechat API synchronization encapsulation
  let status = await this.openSetting('writePhotosAlbum')
  // false indicates rejection again
  if (status === false) return
  // Save to album only when explicitly authorized
  this.canWriteToAlbum = true
  this.saveToPhotosAlbum()
}
Copy the code

conclusion

In addition to recording the implementation of generating share posters, this article mainly explains how to handle user refusal of authorization. Although only the authorization of refusing to save images is said here, the same can be done for other operations.

The first time to write an article, a little messy, later slowly practice it