The applet uses canvas to draw patterns (generate posters, generate distinctive avatars)

The applet uses canvas to draw patterns (generate posters, generate distinctive avatars)

It is common for WeChat mini-programs to generate featured avatars, posters, etc. Below I will introduce the process of implementing this kind of applet.

  1. First select the front end to draw through canvas. This is more cost-effective and efficient.
  2. Small programs are developed using uniapp, which is convenient for later packaging into small programs such as WeChat and Baidu.
  3. You can scan the code to experience my applet to make a personalized avatar,
  4. The following describes the production process of the applet that uses wxml2canvas to generate avatars

Create project

  1. Use HBuilderX to create a uni-app project, you can refer to the uniapp official website.
  2. Download the dependencies used by the project npm init create package.json
  3. yarn add less wxml2canvas

Important steps to generate an avatar

  1. The first idea is to upload a picture that you want to use as your avatar
  2. Then select the element you want to add to the picture, use css positioning, make the picture position overlap, and produce a new effect
  3. Generate pictures with the latest effects and download them.

upload image

Uploading pictures can provide two ideas, one is to directly use WeChat avatars. One is that users upload pictures themselves

  1. Scheme of using WeChat avatar
wxLogin() {
  let _this  = this;
  wx.getUserProfile({
    desc: 'get your avatar',
    success: res => {
      console.log(res)
      _this.headUrl = res.userInfo.avatarUrl
    },
    fail: () => {
      //Deny authorization
      wx.showToast({
        title: 'you declined the request,Can't get your avatar',
        icon: 'error',
        duration: 2000
      });
      return;
    }
  });
},
  1. Users upload pictures themselves, which can be selected directly from the album, or they can use the camera.
pictureClick (selectid) {
  const _this = this;
  let typelist = selectid === 1 ? ['camera'] : ['album']
  uni.chooseImage({
      count: 1,
      sourceType: typelist, //It should be noted that the camera is taken to take pictures, and the album is to open the mobile phone album
      crop: {
        width: 320,
        height: 320
      },
      success: (res)=> {
          _this.$refs.gmyImgCropper.chooseImage(res)
      }
  });
},
  1. For the pictures uploaded by yourself, you need to use canvas to crop them into pictures with the same avatar ratio.
<imgCropper ref="gmyImgCropper" :quality="1" cropperType="fixed" :imgSrc="headUrl" @getImg="getImg"></imgCropper>
// The above is the component for cropping the image, which is relatively large. You can refer to the project source code.

Use css positioning to generate renderings

<view class="head-box" :style="{marginTop: headboxStyle, height: showImgW}">
  <canvas canvas-id="myCanvas" class="myCanvas" :style="{width: showImgW, height: showImgW}"></canvas>
  <view  class="showimg showimg-box head-img-border" :style="{width: showImgW, height: showImgW}">
    <pickerselect  @modelselect="modelselect">
      <view class="showimg normalimgbox" :style="{width: showImgW, height: showImgW, background: currentInfo.iconColor}">
        <image class="headimg normalimg"  src="https://bj.bcebos.com/txy-dev/txy/main/normal.png"/>
      </view>
      <view id="my-canvas" class="my_canvas">
        
        <view class="showimg" :style="{width: showImgW, height: showImgW}">
          <image mode="aspectFill " data-type="image" :data-url="headUrl"  class="headimg my_draw_canvas" :src="headUrl"/>
        </view>
        <view class="showimg" :style="{width: showImgW, height: showImgW}">
          <image mode="heightFix" data-type="image" :data-url="selectimg" class="headimg my_draw_canvas" :src="selectimg"/>
        </view>
      </view>
    </pickerselect>
  </view>
</view>

Use wxml2canvas to generate the final avatar image

import Wxml2Canvas from 'wxml2canvas'
export const startDraw = ()=> {
  let that = this
  // Create wxml2canvas object
  let drawMyImage = new Wxml2Canvas({
    element: 'myCanvas', // canvas id,
    obj: that, // Pass in the this of the current component
    width: 200* 2,
    height: 200 * 2,
    background: '#141415', // Generate the background color of the image
    progress(percent) { // schedule
      console.log(percent);
    },
    finish(url) { // generated image
      wx.hideLoading()
      savePoster(url)
    },
    error(res) { // Reason for failure
      console.log(res);
      wx.hideLoading()
    }
  }, this);
  let data = {
      // get wxml data
      list: [{
          type: 'wxml',
          class: '.my_canvas .my_draw_canvas',  // The root class name of the wxml element to be drawn by my_canvas, the class name of a single element of my_draw_canvas (all single elements to be drawn must be added with this class name)
          limit: '.my_canvas', // wxml element root class name to draw
          x: 0,
          y: 0
      }]
  }
  // draw canvas
  drawMyImage.draw(data, this);
}
export const drawMyCanvas = () => {
  wx.showLoading()
  const that = this
  wx.createSelectorQuery()
    .select('#my-canvas') // id filled in WXML
    .fields({ scrollOffset: true, size: true }, () => {
      startDraw()
    }).exec(() => {
      console.log(888)
    })
} 

Download the generated image locally

export const savePoster = (url) => {
  const that = this
  wx.saveImageToPhotosAlbum({
    filePath: url,
    success: function() {
        wx.showToast({
            title: 'Successfully saved',
            icon: 'none',
            duration: 1500
        });
    },
    fail(err) {
      if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
        wx.showModal({
          title: 'hint',
          content: 'Requires your authorization to save the album',
          showCancel: false,
          success: modalSuccess => {
            wx.openSetting({
              success(settingdata) {
                if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.saveImageToPhotosAlbum({
                        filePath: url,
                        success: function () {
                          wx.showToast({
                            title: 'Successfully saved',
                            icon: 'success',
                            duration: 2000
                          })
                        },
                    })
                } else {
                    wx.showToast({
                        title: 'Authorization failed, please try again later',
                        icon: 'none',
                        duration: 1500
                    });
                }
              }
            })
          }
        })
      }
    }
  })
}

The following is my applet experience code, project code. Hope to learn and progress together with you


[item code] https://gitee.com/he_jing/txy.git

Tags: Javascript Mini Program

Posted by successor on Tue, 08 Nov 2022 14:28:32 +1030