標籤:text idt get 彩色 學習 top 資料 contex stroke
HTML5 Canvas
<canvas>標籤:使用指令碼 (通常是JavaScript)來繪製圖形——預設情況下 <canvas> 元素沒有邊框和內容。
在畫布上(Canvas)畫一個紅色矩形,漸層矩形,彩色矩形,和一些彩色的文字。
<canvas id="myCanvas" width="200" height="100"></canvas>
註:指定一個id屬性 (指令碼中經常引用), width 和 height 屬性定義的畫布的大小,使用 style 屬性來添加邊框:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"> HTML5 canvas 標籤</canvas>
canvas 元素本身是沒有繪圖能力的。所有的繪製工作必須在 JavaScript 內部完成:
<script>var c=document.getElementById("myCanvas");//找到 <canvas> 元素var ctx=c.getContext("2d");//建立 context 對象ctx.fillStyle="#FF0000";//fillStyle屬性可以是CSS顏色,漸層,或圖案。fillStyle 預設設定是#000000(黑色)ctx.fillRect(0,0,160,75);//fillRect(x,y,width,height) 方法定義了矩形當前的填充方式</script>
解析:
(1)找到 <canvas> 元素
(2)建立 context 對象:getContext("2d")
(3)fillStyle屬性:可以是CSS顏色,漸層,或圖案。fillStyle 預設設定是#000000(黑色)
(4)fillRect(x,y,width,height) 方法:定義了矩形當前的填充方式
Canvas 座標
canvas 是一個二維網格。
canvas 的左上方座標為 (0,0)
fillRect 方法擁有參數 (0,0,150,75)。畫布上繪製 150x75 的矩形
Canvas - 路徑
(1)繪製線條——先開始座標,再結束座標,最後用 "ink" 的方法:stroke().。
moveTo(x,y):定義線條開始座標
lineTo(x,y) :定義線條結束座標
例: 定義開始座標(0,0), 和結束座標 (200,100)。最後用"ink" 的方法:stroke() 方法來繪製
<script>var c=document.getElementById("myCanvas");var ctx=c.getContext("2d");ctx.moveTo(0,0);ctx.lineTo(200,100);ctx.stroke();</script>
(2)繪製圓——先開始一條路徑,再定義圓形資料,最後用"ink" 的方法:stroke() 或者 fill()方法來繪製。
beginPath() 方法:開始一條路徑,或重設當前的路徑。
arc(x,y,r,start,stop)方法:定義圓形
<script>var c=document.getElementById("myCanvas");var ctx=c.getContext("2d");ctx.beginPath();ctx.arc(95,50,40,0,2*Math.PI);ctx.stroke();</script>
Canvas - 文本
繪製文本——屬性和方法如下:
font - 定義字型
fillText(text,x,y) - 在 canvas 上繪製實心的文本
<script>var c=document.getElementById("myCanvas");var ctx=c.getContext("2d");ctx.font="30px Arial";ctx.fillText("Hello World",10,50);</script>
strokeText(text,x,y) - 在 canvas 上繪製空心的文本
<script>var c=document.getElementById("myCanvas");var ctx=c.getContext("2d");ctx.font="30px Arial";ctx.strokeText("Hello World",10,50);</script>
Canvas - 漸層
HTML5 學習02——新元素:canvas