<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>無標題文檔</title> <link href="css.css" rel="stylesheet" type="text/css"> <script type="text/javascript" language="jscript" src="js6.js"></script> </head> <body onLoad="pageload();"> <canvas id="cnvMain" width="200px" height="150px"; onClick="cnvClick();"></canvas> </body> </html>
1 @charset "utf-8"; 2 /* CSS Document */ 3 4 body{ 5 font-size:36px; 6 } 7 canvas{ 8 border:dashed 1px #F00; 9 cursor:pointer; 10 } 11 /*增加樣式*/ 12 p{ 13 position: 14 absolute; 15 height:23px; 16 line-height:23px; 17 margin-left:10px; 18 } 19 span{ 20 padding:3px; 21 border:solid 1px #033; 22 background-color:#00F; 23 cursor:pointer; 24 }
1 // JavaScript Document 2 function $$(id){ 3 return document.getElementById(id); 4 5 } 6 function pageload(){ 7 var cnv=$$("cnvMain"); 8 var ctx=cnv.getContext("2d"); 9 //設置邊框 10 ctx.strokeStyle="#3ef3ed"; 11 ctx.strokeRect(30,30,80,80); 12 //設置背景 13 ctx.fillStyle="#ccc"; 14 ctx.fillRect(30,30,80,80); 15 } 16 function cnvClick(){ 17 var cnv=$$("cnvMain"); 18 var ctx=cnv.getContext("2d"); 19 //清空圖形 20 ctx.clearRect(36,36,50,50); 21 }
這個是繪制一個帶邊框的矩形
繪制矩形邊框strokeRect(x,y,width,height);
參數為“x”,“y”為矩形的起點坐標,“width”“height”分別為矩形的寬和高
設置邊框顏色strokeStyle();
清空圖像中的顏色 clearRect();
繪制漸變顏色
1 var c=document.getElementById("myCanvas"); 2 var ctx=c.getContext("2d"); 3 4 var grd=ctx.createLinearGradient(0,0,170,0); 5 grd.addColorStop(0,"black"); 6 grd.addColorStop(1,"white"); 7 8 ctx.fillStyle=grd; 9 ctx.fillRect(20,20,150,100);
createLinearGradient(xStar, yStar,xEnd,YEnd)
xstar和ystar表示漸變開始的坐標
xEnd和YEnd表示漸變結束的坐標
addColorStop(value,color);表示漸變偏移量以及漸變顏色
繪制圓
var cnv=$$("cnvMain");
var cxt=cnv.getContext("2d");
//清除畫布原有圖形1
cxt.clearRect(0,0,280,190);
//開始畫實心圓
cxt.beginPath();
cxt.arc(100,100,50,0,Math.PI*2,true);
cxt.closePath();
//設置填充背景色
cxt.fillStyle="#3ef3ed";
//進行填充
cxt.fill();
各個參數的意思;
1.getContext(“2d”);返回一個用於在畫布上繪圖的環境
2.beginPath():聲明開始繪制路徑
3.closePath();繪制完圖形后關閉繪制路徑。
4.填充(畫實心圓)
1 //設置填充背景色 2 cxt.fillStyle="#3ef3ed"; 3 //進行填充 4 cxt.fill();
描邊(畫空心圓)
//設置邊框色
cxt.strokeStyle="black";
//設置邊框寬度
cxt.lineWidth=5;
//進行描邊
cxt.stroke();

來自w3c


