WeChat applet API gradient (how to draw gradient effect)


Gradient


Gradient can be used to fill a rectangle, circle, line, text, etc. The fill color can be a fixed color.

We provide two methods of color gradient:

  • createLinearGradient(x, y, x1, y1) - Create a linear gradient
  • createCircularGradient(x, y, r) - Creates a gradient starting from the center of the circle

Once we have created a gradient object, we must add two color gradient points .

addColorStop(position, color) The method is used to specify the position and color of the color gradient point. The position must be between 0 and 1.

You can use the setFillStyle() and setStrokeStyle() methods to set the gradient, and then draw and describe it.

Use createLinearGradient()

const ctx = wx.createCanvasContext('myCanvas')

// Create linear gradient
const grd = ctx.createLinearGradient(0, 0, 200, 0)
grd.addColorStop(0, 'red')
grd.addColorStop(1, 'white')

// Fill with gradient
ctx.setFillStyle(grd)
ctx.fillRect(10, 10, 150, 80)
ctx.draw()

201612241107006268.png


##Use createCircularGradient()

const ctx = wx.createCanvasContext('myCanvas')

// Create circular gradient
const grd = ctx.createCircularGradient(75, 50, 50)
grd.addColorStop(0, 'red')
grd.addColorStop(1, 'white')

// Fill with gradient
ctx.setFillStyle(grd)
ctx.fillRect(10, 10, 150, 80)
ctx.draw()

201612241107156589.png