Why

Some of the scenes in the applet need to be drawn with a Canvas with some text, possibly a QR code, and so on. However, if the implementation is completely manual to locate elements in the canvas, the result will be a lot of reusable and difficult to maintain code.

How to use

Using the utils/ wxml2Canvas.js file in the utils directory, the repo itself is a simple example, tweaking some configuration items that can be opened in developer tools.

wxml
<! -- 1. wrapper ID 2. element className 3. If it is text, you need to add the data-text attribute to the element -->
<view class="container" id="wrapper">
  <text class="title draw" data-text="Hello there">Hello there</text>
  <text class="info draw" data-text="Applets are a new open capability that allows developers to quickly develop a small program.">Applets are a new open capability that allows developers to develop applets quickly.</text>
  <view class="image-wrapper draw">
    <image class="draw" src=".. /.. /assets/demo.jpg"/>
  </view>
  
  <button class="generate-btn" bindtap="drawCanvas">generate</button>
</view>
<canvas canvas-id="canvas-map" class="share-canvas"></canvas>

Copy the code
wxss

.container {
  height: 100%;
  box-sizing: border-box;
  padding: 10px 20px;
  display: flex;
  flex-direction: column;
 
} 
.container .title {
  font-size:36px;
  text-align: left;
  margin-bottom: 10px;

}
.container .info {
  font-size: 14px;
  line-height: 18px;
  color: grey;
  text-align: left;
  margin-bottom: 40px;
}
.container .image-wrapper image {
  width: 100%;
}
Copy the code
js
Page({
  drawCanvas: function() {
    const wrapperId = '#wrapper'
    const drawClassName = '.draw'
    const canvasId = 'canvas-map'
    
    wxml2canvas(wrapperId, drawClassName, canvasId).then((a)= > {
      // canvas has been drawn here, you can save the canvas image with wx.canvasToTempFilePath })}})Copy the code

Demo


implementation

The main method is to use the interface wx.createsElectorQuery () provided by the applet to get the node information, and then draw it to the canvas. Currently, it only covers some simple usage scenarios, supporting basic position, font-size, color, image, border-radius, background-color, etc., 🌟🌟

For complex situations, Maybe you can get some inspiration from github.com/niklasvh/ht…

Todo

  • Distinguish between Chinese and English text newlines

Address: github.com/gy134340/wx…