Application of Canvas Drawing in Wechat Program: Generating Personalized Posters

Time:2019-10-9

I. The Background of Canvas Application (Personal Understanding) and Basic Grammar

background

Since 2012, the amount of users accumulated by Wechat at that time has been very large, the introduction of public numbers, of course, large-screen smartphones were also popular at that time, the traditional mass media gradually disappeared, and new media such as Wechat public numbers prevailed. Advertising investment of enterprises began to shift from traditional media such as TV to precise marketing of new media based on circle culture. Even many enterprises, especially Internet enterprises, began to think about how to use the way of user self-dissemination to publicize enterprises and achieve business goals. And a good way for users to spread themselves is to produce personalized posters. For the most common example, I used Keep for the first time because I saw a screenshot of a friend sharing her amount of exercise in a circle of friends. It looked cool to me at that time. It had heart rate, pulse rate, hourly exercise, calories consumed, and a two-dimensional code. Then I clicked and downloaded Keep, which cost almost 0 seconds more than one user. Canvas can be used as a technical means to achieve this process. Therefore, the popularity of canvas is closely related to the precise marketing of enterprises and the self-dissemination of users.
For example, some implementation cases of geek time:

Application of Canvas Drawing in Wechat Program: Generating Personalized Posters Application of Canvas Drawing in Wechat Program: Generating Personalized Posters Application of Canvas Drawing in Wechat Program: Generating Personalized Posters

As you can see from the first picture, the poster for the preview phase of Qcon Global Software Development Conference is at the end of 2017. Then we made a poster for programmers to generate keywords for 2018. The text is very interesting. The second one is a geek time assistant on New Year’s Day 2018. This small program was originally designed for programmers to sign the new year 2018. That’s a column about geek time, including user messages, you can generate a poster, you can forward it, and so on. That’s probably the case.

Basic Grammar

Canvas is essentially an HTML element that can use scripts (usually JavaScript) to draw graphics. The default size is 300 pixels * 150 pixels (width * height, the unit of pixels is px), creating images dynamically through JavaScript context objects. For example, drawing lines, drawing rectangles, painting colors and even generating posters with two-dimensional codes. The principle is a brush-by-brush drawing, drawing a horizontal line, drawing a horizontal line and so on. That is to create a path, draw a path, and then close the path so that it can be painted. His underlying encapsulation is to put it in an array to form an array of paths, pass the array to a method at the bottom of js, and then draw it.

  • Lift a chestnut: Draw a head

Application of Canvas Drawing in Wechat Program: Generating Personalized Posters

First, you need to draw this picture on canvas. For example, if you draw your head as a square, start drawing a picture at (0,0). So at the center of the picture, you take it as the origin, and then you draw a circle. Then you use the canvas grammar to draw an arc and set the visibility within the invisible outside the arc path. At this time, a circular head is formed.

<canvas id="canvas" width="300" height="300"></canvas>
  <script>
    const canvas = document.getElementById('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    img.onload = function() {
      circleImg(ctx, img, 100, 100, 50)
    }
    img.src="https://avatar-static.segmentfault.com/289/811/2898115528-58c35e9b79717_big64"
    function circleImg(ctx, img, x, y, r) {
      ctx.save()
      let d = 2 * r
      let cx = x + r
      let cy = y + r
      ctx.arc(cx, cy, r, 0, 2 * Math.PI)
      ctx.stroke();
      ctx.clip()
      ctx.drawImage(img, x, y, d, d)
      ctx.restore()
    }
    // [canvas] (https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html) in the Wechat applet program is different from that in HTML5 in terms of grammar, such as API.
    // In addition, because canvas in the applet is the highest level of native components, no matter how much Z-index is set, other components in the page can not cover native components.
  </script>

2. Common ways of “creating posters”

We will often see in the circle of friends what fortune telling, personality analysis, estimating your IQ, EQ and so on, are all shared by the user a picture (poster), this picture is made of canvas, which draws a two-dimensional code, two-dimensional code is an array of two or circular nested drawing small black dot users to identify the two-dimensional code, then enter his program, after the process. Running out of the test results ah what, point save time, will generate a personality poster understand. How to generate such personalized posters?

2.1 String Template

There should be cases here.

The main implementation is to agree data format with the server – > make template at the front – > render the server back to the client img with third-party tools
Firstly, we agree with the server about the data format, such as keyword, header URL, nickname and so on. Then we nest all the places where we put the data format with {{}} to tell the back-end location. Then, we cut out the front-end simulation data, such as user. tags, and give this segment of HTML string template to the server. Finally, the server gets the data through a third-party tool such as HTML 2canvas. Picture rendering is returned to the client for display, allowing users to press this picture for a long time and save it to the mobile phone album. This is a more traditional way, which was basically adopted in earlier years.
What are the disadvantages?
First, the third-party tools are not timely maintenance, do not support flex layout, ES6 and other grammars, second, inconvenient debugging, third, high concurrency will cause problems, especially when generating high-definition posters

2.2 Canvas Drawing

Case:’Geek Time Assistant’applet
Main realization: front-end generates posters directly through canvas
Shake the phone to extract the New Year’s signature and jump to the first page. You need to draw the head image, keywords and save buttons. The yellow save button is actually a transparent PNG picture and draw it on it. The button needs to be fixed with an empty, transparent div about the width and size of the button. The click event is added to the div, which is the second canvas to be saved. The second one is a two-dimensional code without saving buttons. Where can I put this canvas with two-dimensional code? One is positioning, giving a particularly large top or left to keep it out of the screen; the other is hierarchy, and the preview of the canvas is really on top of the canvas image, but there are problems. If the version of mobile browser is low, the fixed level will not work, and some Android phones will have problems, sometimes they will float up and not be covered up.
Of course, if we want to save HD maps, we still need to deal with it, that is, zooming, but this is a clumsy method. The best way is to disassemble the image to ensure that the exported canvas is the highest definition and the most traffic-saving for users.
Parsing: In fact, keywords are stochastically picked up on the home page. In the onShow method of index. JS on the home page, the elements to be drawn are cached by wx. getStorageSync, such as keywords (pictures here), keyword parsing words (pictures, after all, canvas of the Wechat applet does not support fonts), and so on. Shake and trigger gravity sensing event wx. onAccelerometerChange to listen for events inside, get user authorization to get the avatar and jump to poster page. Start drawing two pictures directly, one with a two-dimensional code (shakepage1) and one with a button (shakepage2), where the two-dimensional code is a’dead code’, button also covers a view on the basis of the picture, and after drawing, adjust canvas ToTempFilePath to ensure that the strip code is exported. At this time, the strip with the code is hidden through visibility: hidden set by css. Click on the button to trigger saveImageToPhotosAlbum to save the exported image to the mobile phone album. There is a need for authorization to do some processing, such as the user who refuses authorization to click on wx. showModal again to ask the user for authorization. The basic code is as follows: (detailed source code)

wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: this.data.screenWidth,
        height: this.data.screenHeight,
        DestWidth: this. data. screenWidth * this. data. pixelRatio, // pixelRatio is the device's pixel ratio  
        destHeight: this.data.screenHeight * this.data.pixelRatio,
        canvasId: "canvasid",
        success: function(e) {
          console.log(e)
          this.setData({
            BjtempFilePath: E. tempFilePath // Get the path of the image to be saved
          }, function() {});
        },
        fail: function(e) {
          console.log(e);
        }
      })
onUserSaveImageRight: function () {
    console.log("-click-");
    var _this = this;
    if (!wx.saveImageToPhotosAlbum) return wx.showModal({
      Title: "Tips"
      Content: "The current version of Wechat is too low to use this feature. Please upgrade to the latest version of Wechat and try again. “
    }), void console.log("version low");
    wx.getSetting({
      success: function (res) {
        Res. authSetting ["scope. writePhotos Album"]? (console. log ("1 - Authorized Privilege to Save Pictures"), _this. saveimgfn (): wx. authorize({
          scope: "scope.writePhotosAlbum",
          success: function () {
            Console. log ("User to Album - Authorization Successful"), _this. saveimgfn ();
          },
          fail: function () {
            wx.showModal({
              Title: "Tips"
              Content: "Please authorize saving to the system album".
              showCancel: !1,
              success: function (res) {
                res.confirm && wx.openSetting({
                  success: function (res) {
                    res.authSetting["scope.writePhotosAlbum"] ? setTimeout(function () {
                      _this.saveimgfn();
                    }, 500) : wx.showModal({
                      Title: "Tips"
                      Content: "You are not authorized to save the poster to the album. You can take a screenshot of the poster or click the'Save the poster'button again and authorize it."
                      showCancel: !1
                    });
                  }
                });
              }
            });
          }
        });
      }
    });
  },
  saveimgfn: function () {
    var filePath = this.data.bjtempFilePath;
    console.log(filePath), filePath ? wx.saveImageToPhotosAlbum({
      filePath: filePath,
      success: function (res) {
        wx.showToast({
          Title: "Successful Preservation"
          icon: "success",
          duration: 1500
        });
      },
      fail: function () {
        wx.showToast({
          Title: "Save failed"
          icon: "fail",
          duration: 1500
        });
      }
    }) : this.saveImage()

3. Geek Time Small Program – Solution to Generate Various Posters

Comparisons between canvas of Wechat widget and canvas of HTM5

  1. The level Z-index of the microcontroller canvas is invalid, and the microcontroller canvas has the highest level and can not be set up twice.
  2. The microcontroller canvas does not support font function, and special fonts can only be replaced by pictures.
  3. The widget canvas does not support drawing online pictures. It needs to be downloaded and redrawn.
  4. The microcontroller canvas can realize screen adaptation of different sizes
var rpx;
    // Get screen width and adaptive unit
    wx.getSystemInfo({
      success: function(res) {
        rpx = res.windowWidth/750
      },
    })
    // In the rendering method, the parameter can be multiplied by relative unit to achieve self-adaptation.
    const s = wx.createCanvasContext("canvas")
    s.drawImage(Url, 0, 0, 265 * rpx, 262.5 * rpx)

How to export high definition posters and how to package them?

wx.canvasToTempFilePath({
    canvasId: 'image-save',
    x: 0,
    y: 0,
    success: res => {
       wx.saveImageToPhotosAlbum({
         filePath: res.tempFilePath,
         success: () => {
           this.setData({saving: false})
           Utils. success ('save successfully')
           setTimeout(() => {wx.navigateBack()}, 500)
         },
         fail: err => {
           this.setData({saving: false})
           wx.getSetting({
             success: res => {
               if(!res.authSetting || !res.authSetting['scrop.writePhotoAlbum']){
                 wx.openSetting()
               }
             }
           })
         }
       })
    }
})