微信小程序 畫布

2023-04-03 13:49 更新

Canvas 畫布

所有在 canvas 中的畫圖必須用 JavaScript 完成:

WXML:(我們在接下來的例子中如無特殊聲明都會用這個(gè) WXML 為模板,不再重復(fù))

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

JS:(我們在接下來的例子中會將 JS 放在 onReady 中)

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

第一步:創(chuàng)建一個(gè) Canvas 繪圖上下文

首先,我們需要?jiǎng)?chuàng)建一個(gè) Canvas 繪圖上下文 CanvasContext。

CanvasContext 是小程序內(nèi)建的一個(gè)對象,有一些繪圖的方法:

const ctx = wx.createCanvasContext('myCanvas')

第二步:使用 Canvas 繪圖上下文進(jìn)行繪圖描述

接著,我們來描述要在 Canvas 中繪制什么內(nèi)容。

設(shè)置繪圖上下文的填充色為紅色:

ctx.setFillStyle('red')

用 fillRect(x, y, width, height) 方法畫一個(gè)矩形,填充為剛剛設(shè)置的紅色:

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

第三步:畫圖

告訴 canvas 組件你要將剛剛的描述繪制上去:

ctx.draw()

結(jié)果:

坐標(biāo)系

canvas 是在一個(gè)二維的網(wǎng)格當(dāng)中。左上角的坐標(biāo)為(0, 0)。

在上一節(jié),我們用了這個(gè)方法 fillRect(0, 0, 150, 75)。

它的含義為:從左上角(0, 0)開始,畫一個(gè)150 x 75px 的矩形。

代碼示例

我們可以在 canvas 中加上一些事件,來觀測它的坐標(biāo)系

<canvas canvas-id="myCanvas"
  style="margin: 5px; border:1px solid #d3d3d3;"
  bindtouchstart="start"
  bindtouchmove="move"
  bindtouchend="end"/>

<view hidden="{{hidden}}">
  Coordinates: ({{x}}, {{y}})
</view>
Page({
  data: {
    x: 0,
    y: 0,
    hidden: true
  },
  start (e) {
    this.setData({
      hidden: false,
      x: e.touches[0].x,
      y: e.touches[0].y
    })
  },
  move (e) {
    this.setData({
      x: e.touches[0].x,
      y: e.touches[0].y
    })
  },
  end (e) {
    this.setData({
      hidden: true
    })
  }
})

當(dāng)你把手指放到 canvas 中,就會在下邊顯示出觸碰點(diǎn)的坐標(biāo):

漸變

漸變能用于填充一個(gè)矩形,圓,線,文字等。填充色可以不固定為固定的一種顏色。

我們提供了兩種顏色漸變的方式:

  • createLinearGradient(x, y, x1, y1) 創(chuàng)建一個(gè)線性的漸變
  • createCircularGradient(x, y, r) 創(chuàng)建一個(gè)從圓心開始的漸變

一旦我們創(chuàng)建了一個(gè)漸變對象,我們必須添加兩個(gè)顏色漸變點(diǎn)。

addColorStop(position, color) 方法用于指定顏色漸變點(diǎn)的位置和顏色,位置必須位于0到1之間。

可以用setFillStyle 和 setStrokeStyle 方法設(shè)置漸變,然后進(jìn)行畫圖描述。

使用 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()

使用 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()


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號