
將以下代碼存為 .html 直接用瀏覽器開啟即可看到動態鋸齒邊框。
<!doctype html>
<html lang="zh">
<head>
<meta charset="gbk">
<title>鋸齒圖</title>
<script>
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded(){
var x, y;
var theCanvas = document.getElementById("canvas");
var context = theCanvas.getContext("2d");
// 外框
context.strokeStyle = '#00f';
context.lineWidth = 10;
context.strokeRect(0, 0, theCanvas.width, theCanvas.height);
context.fillStyle = "#00f";
// 上下邊鋸齒
for(x=5; x<=theCanvas.width; x+=10){
context.beginPath();
context.arc(x, 5, 5, 0, Math.PI, false); // 上半圓
context.closePath(); context.fill();
context.beginPath();
context.arc(x, theCanvas.height-5, 5, 0, Math.PI, true); // 下半圓
context.closePath(); context.fill();
}
// 左右邊鋸齒
for(y=5; y<=theCanvas.height; y+=10){
context.beginPath();
context.arc(5, y, 5, 0, Math.PI*2, true); // 左全圓
context.arc(theCanvas.width-5, y, 5, 0, Math.PI*2, true); // 右全圓
context.closePath(); context.fill();
}
}
</script>
</head>
<body>
<div style="position: absolute; top: 100px; left: 100px;">
<canvas id="canvas" width="300" height="300"></canvas>
</div>
</body>
</html>
strokeRect 畫出 10px 藍色邊框。false(順時針)畫上半圓,下邊用 true(逆時針)畫下半圓。0 到 2π)。fillStyle = "#00f" 統一藍色,形成連續鋸齒視覺。drawJaggedBorder(canvas, options) 可複用函式。requestAnimationFrame 讓鋸齒旋轉或脈動,增加動態感。Path2D 離屏建立路徑,再 fill,效能更佳。