canvas入門——線段繪製

moveTolineTo

使用canvas繪製一條線段,默認已經拿到canvas的上下文contextcanvas

繪製一條直線須要使用context提供的moveTolineTo方法spa

moveTo是線段的起點,lineTo是線段下一個點,最後使用stroke進行描邊。以下代碼code

context.moveTo(100,100)
context.lineTo(200,200)
context.stroke()

效果圖:blog

1.png

若是一段線段分爲多段,能夠屢次使用lineTo方法,將每一個頂點都填進去就能夠了rem

context.moveTo(100,100)
context.lineTo(200,200)
context.lineTo(200,400)
context.stroke()

效果圖:it

2.png

strokeStylelineWidth

content還提供了strokeStylelineWidth兩個方法,這兩個方法能夠的做用是描邊顏色線寬class

ctx.moveTo(100, 100)
ctx.lineTo(200, 200)
ctx.lineTo(200, 400)
ctx.strokeStyle = 'red'
ctx.lineWidth = 5
ctx.stroke()

效果圖方法

3.png

若是我想繪製兩條不一樣的線段呢?使用moveTo就能開始新的一條線段繪製im

ctx.moveTo(100, 100)
ctx.lineTo(200, 200)
ctx.lineTo(200, 400)
ctx.strokeStyle = 'red'
ctx.lineWidth = 5
ctx.stroke()

ctx.moveTo(300, 100)
ctx.lineTo(400, 200)
ctx.lineTo(400, 400)
ctx.strokeStyle = 'blue'
ctx.lineWidth = 10
ctx.stroke()

效果圖:總結

4.png

看到效果圖以後,發現和預想的不同啊,爲何第一段代碼沒有生效?

這是由於canvas是基於狀態繪製的,上面一段代碼寫了strokeStyle = 'red',而後stroke繪製;而後下面開始一段新的線段繪製寫了strokeStyle = 'blue',在寫這句話的時候,已經把上面的red改爲了blue,使用最後一個stroke又進行繪製了。

也就是說無論你上面寫了多少屬性,只要最後一個stroke前對屬性改動,都會被覆蓋。

怎麼解決這個問題呢?

beginPathclosePath

context提供了beginPathclosePath,這兩個方法是告訴canvas我要開始繪製和結束繪製了,你不要給我隨便改變屬性

ctx.beginPath()
ctx.moveTo(100, 100)
ctx.lineTo(200, 200)
ctx.lineTo(200, 400)
ctx.strokeStyle = 'red'
ctx.lineWidth = 5
ctx.closePath()
ctx.stroke()

ctx.beginPath()
ctx.moveTo(300, 100)
ctx.lineTo(400, 200)
ctx.lineTo(400, 400)
ctx.strokeStyle = 'blue'
ctx.lineWidth = 10
ctx.closePath()
ctx.stroke()

效果圖:

5.png

這裏有個比較奇怪的是,最後我沒有回到原點呀,爲何最後給我連起來了呢?

這是由於使用了closePath這個方法,使用closePath時,若是最後一個點沒有回到起始位置,它會爲你把首尾鏈接起來。

若是以後想鏈接起來,能夠不用寫closePath,其實,只要寫了beginPathcanvas就已經知道了你要從新繪製新線段了。

ctx.beginPath()
ctx.moveTo(100, 100)
ctx.lineTo(200, 200)
ctx.lineTo(200, 400)
ctx.strokeStyle = 'red'
ctx.lineWidth = 5
ctx.stroke()

ctx.beginPath()
ctx.moveTo(300, 100)
ctx.lineTo(400, 200)
ctx.lineTo(400, 400)
ctx.strokeStyle = 'blue'
ctx.lineWidth = 10
ctx.stroke()

效果圖:

6.png

這裏要說明的一點是,寫在stroke是繪製,stroke上面的那些都是狀態,把狀態寫在stroke下面固然是不生效的的。

7.png

最後

總結一下:

  • 使用moveTolineTo繪製線段
  • beginPath開始新的線段繪製
  • closePath繪製線段首尾未相連,它會連起來
  • canvas繪製是基於狀態繪製的,繪製以後線段的屬性就不能被改變了。
相關文章
相關標籤/搜索