1. 程式人生 > >畫布canvas標籤,並且在畫布上畫簡單的形狀

畫布canvas標籤,並且在畫布上畫簡單的形狀

今天整畫布,半天下來老是錯,結果:

<canvas id = 'c1' width="400" height="400">
    <p>瀏覽器不支援</p><!--width:300 height:150-->
</canvas>
原來畫布的寬度和高度需要在標籤定義的時候確定,並且後面是不能帶有px這個單位的,比如:
錯誤的定義:
#c1
{
    background: white;
position: absolute;
left: 200px;
top: 10px;
width:400px;
    height:400px;
}
oGC.fillStyle 
= 'yellow'; oGC.fillRect(10,10,200,100);//(x,y,w,h)這個是畫一矩形,預設的填充的是黑色
還應該知道的是這樣矩形填充的顏色必須在畫矩形之前做oGC.strokeStyle = 'red';//這個是表示劃線的顏色設定
這個也是畫一個矩形,這個是預設沒有填充的,或者說是白色的
oGC.strokeRect(10.5,100.5,100,80);
oGc.fillStyle="green";
oGc.strokeStyle="red";
oGc.beginPath();//宣告
oGc.moveTo(10,20);//開始位置
oGc.lineTo(60,80);//目標位置
oGc.stroke();
oGc.lineTo(100,190); oGc.stroke(); oGc.lineTo(10,20); oGc.stroke();
 oGc.fill();//想要填充指定的顏色,需要用到fillStyle="green"
//            還有就是fill(),並且這個fill()是必須在所有的stroke執行之後才進行執行的
oGc.closePath();在畫布上面畫線是,首先是beginPath(),moveTo是起點,lineTo是下一個點
stroke()是表示執行畫
<!DOCTYPE html>
<html lang="en">
<head>
<!--畫布-->
<meta charset="UTF-8"> <title>Canvas</title> <style> body { background: gray; } #c1 { background: white; position: absolute; left:200px; top:20px; /*box-shadow: 4px 4px 4px black;*/ } </style> <script> window.onload=function(){ // 獲取畫布 var oCan=document.getElementById("c1"); var oGc=oCan.getContext("2d"); // oGc.fillStyle="yellow";//給內部填充顏色 // oGc.fillRect(10,10,200,100);//畫一個矩形預設的填充為黑色 // 填充一個矩形,座標,寬和高 // oGc.fillStyle='red';//填充矩形要在該矩形畫之前進行 // oGc.fillRect(0,0,100,50); // oGc.strokeStyle="red"; // oGc.strokeRect(10.5,100.5,100,80);//前面是 // oGc.strokeRect(10.5,100.5,100,80); // // oGc.strokeText("你好"); oGc.fillStyle="green"; oGc.strokeStyle="red"; oGc.beginPath();//宣告 oGc.moveTo(10,20);//開始位置 oGc.lineTo(60,80);//目標位置 oGc.stroke(); oGc.lineTo(100,190); oGc.stroke(); oGc.lineTo(10,20); oGc.stroke(); oGc.fill();//想要填充指定的顏色,需要用到fillStyle="green" // 還有就是fill(),並且這個fill()是必須在所有的stroke執行之後才進行執行的 oGc.closePath(); } </script> </head> <body> <canvas id="c1" width="400" height="400"> <!--預設的大小是width=300,height=150--> </canvas> </body> </html>