WeChat Open Platform

Mini Programs Documentation

Drawing on the canvas

All drawings in <canvas/> must be completed using JavaScript:

WXML: (We have used WXML as the template in all of the following examples unless stated specifically, this will not be repeated)

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

JS: (In the following examples we will put JS in onLoad)

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

Step 1: Create a canvas drawing context

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

CanvasContext is an object that is built into Mini Programs, it has a few drawing methods:

const ctx = wx.createCanvasContext('myCanvas')

Step 2: Use the canvas drawing context to describe the drawing

Next, we describe what content we want to draw in the canvas.

Setting the drawing context fill color as red:

ctx.setFillStyle('red')

Using the fillRect(x, y, width, height) method to draw a rectangle, the fill is the red that we have just set:

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

Step 3: Drawing

Telling the <canvas/> component you want what you just described to be drawn:

ctx.draw()

Result: