欧美日韩精品一区二区在线线,一级无码在线收看,精品国产高清91,久久精品欧美电影

# 舊版 Canvas 畫布

本文檔介紹的是舊版 Canvas 接口,不支持同層渲染,性能較差。

建議參考 舊版 Canvas 遷移指南 遷移至新版 Canvas 2D 接口。

# Canvas 繪制步驟

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

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

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

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

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

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

首先,我們需要創(chuàng)建一個 Canvas 繪圖上下文 CanvasContext

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

const ctx = wx.createCanvasContext('myCanvas')

# 第二步:使用 Canvas 繪圖上下文進行繪圖描述

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

設置繪圖上下文的填充色為紅色:

ctx.setFillStyle('red')

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

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

# 第三步:畫圖

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

ctx.draw()

# 結果:

# 坐標系

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

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

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

# 代碼示例

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

<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
    })
  }
})

當你把手指放到 canvas 中,就會在下邊顯示出觸碰點的坐標:

# 漸變

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

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

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

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

可以用setFillStylesetStrokeStyle 方法設置漸變,然后進行畫圖描述。

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