今天,我想來畫一下太極。并讓它轉(zhuǎn)動特幔。
用畫布畫出來蓖柔,這樣 我先把代碼寫出來 并旁邊加注釋辰企,這樣就能看的更明白了
代碼及注釋如下:
首先在body內(nèi)做好畫布
<canvas id="canvas" width="500" height="500"></canvas>
然后 在javaScript標(biāo)簽內(nèi)畫出相對應(yīng)的代碼
var deg = 0; ?//定義一個角度,初始值為零
var w = 'white'; ? 定義兩變量 ?一個為白色况鸣,一個為黑色
var b = 'black';
// 用一個函數(shù)方法封裝所畫出來的太極蟆豫,
function draw(){
var canvas = document.getElementById('canvas'); ? //獲取元素
var ctx = canvas.getContext('2d');
var posx = Math.sin(deg)*100;
var posy = Math.cos(deg)*100; ?// 這是正弦,余弦值懒闷,目的是找出太極內(nèi)小半圓的 原點在畫布的位置
ctx.clearRect(0,0,500,500); ?// 當(dāng)然畫出后運行方法時要不停地消除十减,否則內(nèi)存會變大
// ?接下來就是不斷地畫出來 ,邏輯比較簡單 不解釋愤估,主要是找出相對應(yīng)的黑白顏色的圓和半圓坐標(biāo)帮辟,不斷地畫出來
ctx.beginPath();
ctx.arc(250,250,200,0,2*Math.PI,false);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = b;
ctx.arc(250,250,200,0.5*Math.PI+deg,1.5*Math.PI+deg,false);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = w;
ctx.arc(250,250,200,0.5*Math.PI+deg,1.5*Math.PI+deg,true);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = w;
ctx.arc(250-posx,250+posy,100,0.5*Math.PI+deg,1.5*Math.PI+deg,false);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = b;
ctx.arc(250+posx,250-posy,100,0.5*Math.PI+deg,1.5*Math.PI+deg,true);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = w;
ctx.arc(250+posx,250-posy,10,0,2*Math.PI,true);
ctx.fill();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = b;
ctx.arc(250-posx,250+posy,10,0,2*Math.PI,true);
ctx.fill();
ctx.closePath();
deg+=0.1; ?// 角度不斷地加,會在定時器的作用下做出太極不斷轉(zhuǎn)的動畫效果
}
setInterval(draw,100);
好玩焰,就到這里由驹。