新聞中心
Canvas 畫布
所有在 canvas 中的畫圖必須用 JavaScript 完成:

10年積累的成都做網(wǎng)站、網(wǎng)站制作經(jīng)驗,可以快速應對客戶對網(wǎng)站的新想法和需求。提供各種問題對應的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡服務。我雖然不認識你,你也不認識我。但先網(wǎng)站設計后付款的網(wǎng)站建設流程,更有洪湖免費網(wǎng)站建設讓你可以放心的選擇與我們合作。
WXML:(我們在接下來的例子中如無特殊聲明都會用這個 WXML 為模板,不再重復)
JS:(我們在接下來的例子中會將 JS 放在 onReady 中)
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 中加上一些事件,來觀測它的坐標系
Coordinates: ({{x}}, {{y}})
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 中,就會在下邊顯示出觸碰點的坐標:
漸變
漸變能用于填充一個矩形,圓,線,文字等。填充色可以不固定為固定的一種顏色。
我們提供了兩種顏色漸變的方式:
- createLinearGradient(x, y, x1, y1) 創(chuàng)建一個線性的漸變
- createCircularGradient(x, y, r) 創(chuàng)建一個從圓心開始的漸變
一旦我們創(chuàng)建了一個漸變對象,我們必須添加兩個顏色漸變點。
addColorStop(position, color) 方法用于指定顏色漸變點的位置和顏色,位置必須位于0到1之間。
可以用setFillStyle 和 setStrokeStyle 方法設置漸變,然后進行畫圖描述。
使用 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()
網(wǎng)頁標題:創(chuàng)新互聯(lián)小程序教程:微信小程序畫布
URL分享:http://www.fisionsoft.com.cn/article/cdiepee.html


咨詢
建站咨詢
