自學HTML5第四節(canvas畫布詳解)

來源:互聯網
上載者:User

標籤:style   color   os   使用   ar   java   strong   sp   on   

canvas畫布好像可是說是HTML5的精華了,一定要學好,嗯嗯,絢麗的東西就要從基礎的開始。。。。

先看看啥玩意叫做canvas 

什麼是 Canvas?

HTML5 的 canvas 元素使用 JavaScript 在網頁上繪製映像。

畫布是一個矩形地區,您可以控制其每一像素。

canvas 擁有多種繪製路徑、矩形、圓形、字元以及添加映像的方法。

 

建立一個canvas

向 HTML5 頁面添加 canvas 元素。

規定元素的 id、寬度和高度:

<canvas id="myCanvas" width="200" height="100"></canvas>

矩形的繪製

canvas 元素本身是沒有繪圖能力的。所有的繪製工作必須在 JavaScript 內部完成:

<script type="text/javascript">var c=document.getElementById("myCanvas");    //使用 id 來尋找 canvas 元素:var cxt=c.getContext("2d");      //建立 context 對象:getContext("2d") 對象是內建的 HTML5 對象,擁有多種繪製路徑、矩形、圓形、字元以及添加映像的方法
cxt.fillStyle="#FF0000"; //代碼繪製一個紅色的矩形:
cxt.fillRect(0,0,150,75);</script>

  1. fillRect()

  2. strokeRect()

線條

通過指定從何處開始,在何處結束,來繪製一條線:

<script type="text/javascript">var c=document.getElementById("myCanvas");var cxt=c.getContext("2d");cxt.moveTo(10,10);cxt.lineTo(150,50);cxt.lineTo(10,50);cxt.stroke();</script>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">Your browser does not support the canvas element.</canvas>

1. lineWidth
 圓形

 

<script type="text/javascript">var c=document.getElementById("myCanvas");var cxt=c.getContext("2d");cxt.fillStyle="#FF0000";cxt.beginPath();cxt.arc(70,18,15,0,Math.PI*2,true);cxt.closePath();cxt.fill();</script>

 

漸層
<script type="text/javascript">var c=document.getElementById("myCanvas");var cxt=c.getContext("2d");var grd=cxt.createLinearGradient(0,0,175,50);grd.addColorStop(0,"#FF0000");grd.addColorStop(0.5,"#00FF00");
grd.addCOlorStop(1,"#212121");cxt.fillStyle=grd;cxt.fillRect(0,0,175,50);</script>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">Your browser does not support the canvas element.</canvas>
映像
<script type="text/javascript">var c=document.getElementById("myCanvas");var cxt=c.getContext("2d");var img=new Image()img.src="flower.png"cxt.drawImage(img,0,0);</script>

 



自學HTML5第四節(canvas畫布詳解)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.