Small program canvas drawing business card

Time:2021-10-8

Drawing business cards with cancas involves technical prototype avatar, text beyond line feed, font size, color and background map
Wxml page content

<view class="pages">
  <canvas  canvas-id="shareKapian" style="width:{{width}}px;height:{{height}}px;"></canvas>
</view>

Wxjs content
Online pictures need to convert the online path to a local path through the localimge function.
Step: first turn on the camera permission canvaskapian — > then start drawing the business card canvasclick — > and finally download the business card downfn

Page({ 
  data: {
    width: 320,
    height: 300,
    Isdisable: false, // prevent multiple clicks
  }, 
  onLoad: function (options) {
    this.canvasKapian();
  },
  //Draw business card
  canvasKapian() { 
    wx.getSetting({
      success: res => {
        console.log(res);
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: res => {
              this.canvasClick();
            },
            fail: err => {
              wx.showModal({
                Title: "prompt",
                Content: 'failed to save the picture. You need to open the photo album permission and save it again. Do you want to open it?',
                success: res => {
                  if (res.confirm) {
                    wx.openSetting({
                      success: (res) => {
                        if (res.authSetting['scope.writePhotosAlbum']) {
                          this.canvasClick();
                        } else {
                          wx.showToast({
                            Title: 'failed to obtain permission, unable to save pictures or videos to your album using',
                            icon: 'none'
                          })
                        }
                      },
                    })
                  }
                }
              })
            }
          })
        } else {
          this.canvasClick();
        }
      }
    })
  },
  canvasClick() {
    this.setData({
      isDisable: true
    })
    wx.showLoading({
      Title: 'business card generation...',
    })
    // let image1 = this.localImge(this.data.background);
    // let image2 = this.localImge(this.data.wxCode);
    // let image3 = this.localImge(this.data.headerImg);
    // Promise.all([image1, image2, image3]).then(res => {
    //   let background1 = res[0];
    //   let wxCode1 = res[1];
    //   let headerImg1 = res[2];
      const ctx = wx.createCanvasContext("shareKapian");
      ctx.setFillStyle("#22DDB8"); // Background color
      //Background map
      ctx.drawImage('../../image/bc.jpg', 0, 0, this.data.width, this.data.height);
      ctx.fillRect(0, 0, this.data.width, this.data.height); 
      let top = 30; 
      let left = 30;
      //Avatar
      this.circleImg(ctx, '../../image/bc.jpg', left, top, 20)
      //Activities
      ctx.fillStyle="#9B712E";
      ctx.setFontSize(18);
      ctx.font = 'bold'; 
      ctx.fillText('bingxiaoxiao', left + 50, top);
      //Introduction
      ctx.setFontSize(14);  
      This. DrawText (CTX, 'on the morning of July 24, 2020, the Chinese Ministry of foreign affairs informed the U.S. Embassy in China that China decided to revoke the establishment and operation license of the U.S. Consulate General in Chengdu and put forward specific requirements for the Consulate General to stop all business and activities.', left + 50, top + 25, 0, 135)
      ctx.draw(false, () => {
        wx.canvasToTempFilePath({
          canvasId: "shareKapian",
          success: res => {
            wx.hideLoading();
            this.setData({
              catShopUrl: res.tempFilePath
            });
            this.downFn();
          },
          fail: err => {
            Console.log ('generation failed ', ERR);
          }
        });
      });
    // }).catch(err => {
    //   console.log(err);
    //   wx.hideLoading();
    //   wx.showToast({
    //Title: 'picture loading failed, please return and try again',
    //     icon: 'none'
    //   })
    // })
  },
  //Save picture
  downFn() {
    let imgurl = '';
    wx.showLoading({
      Title: 'saving...',
    })
    imgurl = this.data.catShopUrl;
    wx.saveImageToPhotosAlbum({
      filePath: imgurl,
      success: res => {
        wx.hideLoading()
        wx.showToast({
          Title: "save it successfully and share it with the circle of friends from the album",
          icon: "none",
          duration: 4000
        });
        this.setData({
          isDisable: false
        }) 
      },
      fail: function (err) {
        console.log(err)
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") { 
          wx.hideLoading();
          wx.showModal({
            Title: "prompt",
            Content: 'failed to save the picture. You need to open the photo album permission and save it again. Do you want to open it?',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  complete: (res) => {
                    console.log(res);
                  },
                })
              }
            }
          })
        }
      }
    });
  },
  //Generate local picture
  localImge: function (src) {
    console.log('src', src);
    return new Promise(function (resolve, reject) {
      wx.downloadFile({
        url: src,
        success: function (res) {
          resolve(res.tempFilePath);
        },
        fail: err => {
          reject(err)
        }
      });
    });
  },
  //Line break exceeded
  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var lastSubStrIndex = 0; // Index of the string to be intercepted each time
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); // Draw intercept
        initHeight += 16; // 16 is the height of the font to prevent text overlap
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      If (I = = str.length - 1) {// draw the rest
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    //Title border bottom line distance from top
    titleHeight = titleHeight + 10;
    return titleHeight
  },
  //Circular picture
  circleImg: function (ctx, img, x, y, r) {
    ctx.save()
    ctx.beginPath()
    var d = 2 * r;
    var cx = x + r;
    var cy = y + r;
    ctx.arc(cx, cy, r, 0, 2 * Math.PI);
    ctx.clip();
    ctx.drawImage(img, x, y, d, d);
    ctx.restore()
  },
})

design sketch:
Small program canvas drawing business card

Recommended Today

Start with Hotspot source code from Thread.start

native start0 is traced to the hotspot source code private void native start0(); The principle of native is to call JNI, and the convention of Hotspot source code is, usually one Xxx.java corresponds to one Xxx.c, Here are three examples: Java class Path relative to the OpenJDK source java.lang.Thread jdk/src/share/native/java/lang/Thread.c java.lang.String jdk/src/share/native/java/lang/String.c java.lang.System jdk/src/share/native/java/lang/System.c So […]