WeChat Mini Program Development Actual Combat (17): Draw a smiling face on canvas

The canvas of the applet allows drawing basic graphics such as straight lines and circles. The canvas needs to use the <canvas> tag. For example, the following layout code uses the <canvas> tag to define a 300*200 canvas.

<canvas style="width: 300px; height: 200px;" canvas-id="mycanvas"></canvas>

An important attribute canvas-id is used in the <canvas> tag. This attribute is used to specify the ID of the canvas. There cannot be two or more canvases with the same ID on the same page.

We can draw a smiley face on the canvas with the following JavaScript code.

Page({
  onReady: function (e) {
 
    // 使用 wx.createContext 获取绘图上下文 context
    var context = wx.createContext()
 
    context.setStrokeStyle("#0000ff")
    context.setLineWidth(5)
    context.rect(0, 0, 200, 200)
    context.stroke()
    context.setStrokeStyle("#ff00ff")
    context.setLineWidth(2)
    context.moveTo(160, 100)
    context.arc(100, 100, 60, 0, 2 * Math.PI, true)
    context.moveTo(140, 100)
    context.arc(100, 100, 40, 0, Math.PI, false)
    context.moveTo(85, 80)
    context.arc(80, 80, 5, 0, 2 * Math.PI, true)
    context.moveTo(125, 80)
    context.arc(120, 80, 5, 0, 2 * Math.PI, true)
    context.stroke()
 
    // 调用 wx.drawCanvas,通过 canvasId 指定在哪张画布上绘制,通过 actions 指定绘制行为
    wx.drawCanvas({
      canvasId: 'mycanvas',
      actions: context.getActions() // 获取绘图动作数组
    })
  }
})

When the system is loaded, it will call the onReady function, in which the context is used to draw the corresponding graphics, and finally the wx.drawCanvas method is used to specify which canvas to draw the image on. The drawing effect is shown in Figure 1.

Figure 1 Canvas demo effect

Among them, the second parameter actions of the wx.drawCanvas method specifies some functions for setting the drawing style used by the current drawing behavior. If you output the information returned by the context.getActions method to the Console, you will see the log information shown in Figure 2.

Figure 2 Log information output by the context.getActions method

If you are interested in this article, you can add teacher Li Ning's WeChat public account (unitymarvel):

Follow the official account of Geek Origin to get more free technical videos and articles.

Guess you like

Origin blog.csdn.net/nokiaguy/article/details/107805235