下列給出html代碼:
<canvas id="canvas" width="480px" height="480px"></canvas>
<span id="message"><span id="cycle" class="message2"></span> <span class="message2">:圈/秒</span></span></br>
<button id="inc">加速</button>
<button id="dec">減速</button>
<button id="stop">停止</button>
</body>```
我們將在<span>中實時更新太極圓旋轉的速度,三個按鈕<button>元素分別實現太極圓旋轉的加速,減速,暫停/開始操作。
下面是相關的CSS代碼:
message{
position: absolute;
left: 450px;
top: 50px;
width: 120px;}
.message2{
display:inline-block;
width:60px;}
cycle{
text-align:right;}
button{
height: 30px;
width: 60px;
margin-left: 75px;
}
利用絕對定位,根據top,left屬性我們可以把顯示太極圓的<span>元素,放到<canvas>元素的左上角。
OK,說完了,HTML(結構層)和CSS(表現層),接下來我們就來講講JavaScript(動作層)的內容。
首先我們需要一個太極圖像,我將通過JS編程來得到太極圓。
var taiji=document.getElementById("canvas");
利用DOM中的getElementById方法來得到canvas的引用,id值為前面html代碼中<canvas>元素中的id屬性的值。
我們就像一個painter拿到了自己的畫板(引用),可是這個畫板比較特別,它not only can畫2d效果,but also 畫3d效果,我們畫的是一個平面太極畫,所以我們就利用getContext("2d")方法來說明自己將進行2d繪圖:
var tua=taiji.getContext("2d");
獲得2d上下文好比得到一張白紙,我們就可以畫太極了!!
tua.beginPath();
//路徑開始
tua.translate(240,240);
//我們將畫布的原點平移到畫布中心點出,畫布為一個480*480的正方形
tua.moveTo(0,-200);
//將起點移到點(0,-200)處,注意前面我們已經將畫布的坐標原點移到了原來的(240,240)處
tua.arc(0,-100,100,3/2Math.PI,1/2Math.PI,true);
tua.arc(0,100,100,3/2Math.PI,1/2Math.PI,false);
//分別畫分割太極的兩個半圓
tua.arc(0,0,200,1/2Math.PI,3/2Math.PI,true);
//太極大圓的一半
tua.fillStyle = "black";
//設置填充色
tua.fill();
//進行填充
tua.arc(0,0,200,3/2Math.PI,1/2Math.PI,true);
//太極大圓的另一半
tua.stroke();
//將上述路徑用實線繪制(描邊),我們還可以利用fillStroke屬性設置繪制線的顏色。用lineWidth屬性設置線寬等,如tua.fillStroke="blue",tua.lineWidth=4;
tua.closePath();
//結束路徑
上面之所以我們一半一半的畫太極的大圓,是因為我們需要對太極圓進行填充(黑色),我們先將黑色的勾玉畫完,在畫白色的勾玉
tua.beginPath();
tua.arc(0,-100,20,0,2*Math.PI,true);
tua.fillStyle = "white";
tua.fill();
tua.stroke();
tua.closePath();
//畫黑色勾玉中的白色小圓
tua.beginPath();
tua.arc(0,100,20,0,2*Math.PI,true);
tua.fillStyle = "black";
tua.fill();
tua.stroke();
tua.closePath();
//畫白色勾玉中的黑色小圓
下面我主要介紹一下,arc()方法的使用:
arc()方法接受六個參數
arc(x,y,radius,startAngle,endAngle,direction)
x,y:在當前畫布中的所畫圓坐標
radius:所畫圓的坐標
startAngle,endAngle:起始角度及終點角度
direction:可選值為兩個true和false,true表示從起點到終點逆時針轉,false表示的當然是順時針了
默認的是把圓心的右端,作為零度角。