
逐幀計算座標,用 arc 繪製太極的陰陽魚與小圓點,適合理解 Canvas 基礎繪圖邏輯。
<!DOCTYPE HTML>
<html>
<body>
<canvas id="myCanvas" width="500" height="500">您的瀏覽器不支援 canvas</canvas>
<script>
var deg = 0, r = 30, rl = 100;
function drawTaiji() {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var colorA = "rgb(0,0,0)", colorB = "red";
var px = Math.sin(deg) * r;
var py = Math.cos(deg) * r;
ctx.clearRect(0, 0, 300, 300);
// 陰魚
ctx.fillStyle = colorA;
ctx.beginPath();
ctx.arc(rl, rl, 60, 0.5*Math.PI+deg, 1.5*Math.PI+deg, true);
ctx.closePath(); ctx.fill();
// 陽魚
ctx.fillStyle = colorB;
ctx.beginPath();
ctx.arc(rl, rl, 60, 1.5*Math.PI+deg, 0.5*Math.PI+deg, true);
ctx.closePath(); ctx.fill();
// 小陰圓
ctx.fillStyle = colorB;
ctx.beginPath();
ctx.arc(rl+px, rl-py, 30, 0.5*Math.PI+deg, 1.5*Math.PI+deg, true);
ctx.closePath(); ctx.fill();
// 小陽圓
ctx.fillStyle = colorA;
ctx.beginPath();
ctx.arc(rl-px, rl+py, 30, 1.5*Math.PI+deg, 0.5*Math.PI+deg, true);
ctx.closePath(); ctx.fill();
// 陰眼
ctx.fillStyle = colorA;
ctx.beginPath();
ctx.arc(rl+px, rl-py, 8, 0, 2*Math.PI, true);
ctx.closePath(); ctx.fill();
// 陽眼
ctx.fillStyle = colorB;
ctx.beginPath();
ctx.arc(rl-px, rl+py, 8, 0, 2*Math.PI, true);
ctx.closePath(); ctx.fill();
deg += 0.1;
}
setInterval(drawTaiji, 100);
</script>
</body>
</html>
將繪圖原點移至中心,再用 rotate 旋轉整個座標系,程式碼更模組化、易維護。
<!DOCTYPE HTML>
<html>
<body>
<canvas id="myCanvas" width="500" height="500">您的瀏覽器不支援 canvas</canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var angle = 0, count = 360;
var clrA = '#000', clrB = 'red';
function taiji(x, y, radius, angle, wise) {
angle = angle || 0;
wise = wise ? 1 : -1;
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle);
ctx.fillStyle = clrA;
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI, true);
ctx.fill();
ctx.fillStyle = clrB;
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI, false);
ctx.fill();
ctx.fillStyle = clrB;
ctx.beginPath();
ctx.arc(wise * -0.5 * radius, 0, radius/2, 0, Math.PI*2, true);
ctx.fill();
ctx.fillStyle = clrA;
ctx.beginPath();
ctx.arc(wise * 0.5 * radius, 0, radius/2, 0, Math.PI*2, false);
ctx.arc(wise * -0.5 * radius, 0, radius/10, 0, Math.PI*2, true);
ctx.fill();
ctx.fillStyle = clrB;
ctx.beginPath();
ctx.arc(wise * 0.5 * radius, 0, radius/10, 0, Math.PI*2, true);
ctx.fill();
ctx.restore();
}
setInterval(function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
taiji(200, 200, 50, Math.PI * (angle/count) * 2, true);
angle = (angle + 5) % count;
}, 50);
</script>
</body>
</html>
| 特性 | 方法一 | 方法二 |
|---|---|---|
| 程式結構 | 單一巨函數 | 模組化函數 taiji() |
| 座標計算 | 手動三角函數 | 靠 translate/rotate 由瀏覽器處理 |
| 擴充性 | 較難 | 易於新增多個太極、變速、反向 |
| 效能 | 相近 | 相近 |
兩種寫法各有優劣:初學者可從方法一理解 arc 參數含義;實務專案建議採用方法二,善用 Canvas 狀態堆疊(save/restore)與座標變換,打造可維護的動畫元件。