HTML5 canvas beginPath() 方法

來源:互聯網
上載者:User

標籤:

beginPath() 方法開始一條路徑,或重設當前的路徑。w3school上的解釋!

 

路徑是canvas裡很重要的一個概念,剛開始學canvas的人對路徑理解不是很深,他們在用canvas的時候會亂用beginPath(),今天做了一個小demo來說明一下路徑

<html lang="en-US">  <canvas id=myCanvas width=500px height=500px></canvas>    <script>      var myCanvas = document.getElementById("myCanvas");      var context = myCanvas.getContext("2d");            context.fillStyle = "#e4e4e4";      context.fillRect(0,0,500,500);        context.beginPath();            context.moveTo(100,100);      context.lineTo(200,100);      context.strokeStyle = "red";      context.stroke();        context.beginPath();      context.moveTo(100,200);      context.lineTo(200,200);      context.strokeStyle = "blue";      context.stroke();  </script>  </html>  

  如果不對這段代碼做改動的話,顯示的一條紅線和藍線,大家會想,這有什麼好說的呢,肯定是這樣啊。

接下來我們把第二個的context.stroke()注釋起來,你會發現最後的結果只是一條藍線,因為第一個路徑沒有stroke(),緊接著

context.beginPath(); 

就重新開闢了一個路徑,使得只能畫了第二個路徑的直線,大家是不是發現越來越神奇了呢?

 

緊接著我把不注釋context.stroke(),而把context.beginPath()注釋起來,你發現什麼了?很奇妙,你發現了一條紫線和藍線,為什麼呢?原來是因為沒有開闢新的路徑,所以第二個stroke()又重新畫了第一條直線,並且用了藍色,而第一個stroke()已經用紅色畫了第一條直線了,藍色和紅色的結合就變成了紫色,第二

context.stroke();繪畫了藍色。

 

你想想,如果把beginPath()和stroke()都注釋起來會怎麼樣呢?兩條藍色的直線,you are good

HTML5 canvas beginPath() 方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.