WeChat applet API drawing introduction (how to draw on Canvas)


Drawing on Canvas


All drawings in <canvas/> must be done with JavaScript:

WXML: (We are connecting If there is no special declaration in the following examples, this WXML will be used as the template and will not be repeated)

<canvas canvas-id="myCanvas" style="border: 1px solid;"/>

JS: (We will put JS in onLoad in the following examples)

const ctx = wx.createCanvasContext('myCanvas')
ctx.setFillStyle('red')
ctx.fillRect(10, 10, 150, 75)
ctx.draw()

Step one: Create a Canvas drawing context

First, we need to create a Canvas drawing context CanvasContext.

CanvasContext is an object built into the applet and has some drawing methods:

const ctx = wx.createCanvasContext('myCanvas')

Step 2: Use the Canvas drawing context to describe drawing

Next, let’s do Describe what is to be drawn in the Canvas.

Set the fill color of the drawing context to red:

ctx.setFillStyle('red')

Use the fillRect(x, y, width, height) method to draw a rectangle and fill it with the red just set :

ctx.fillRect(10, 10, 150, 75)

Step 3: Draw

Tell the<canvas/> component that you want to draw the description just now:

ctx.draw()

Result :

201612241053373520.png##