可直接複製粘貼運行 <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <titl ...
可直接複製粘貼運行
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>canvas</title>
</head>
<body>
<canvas width="1000" height="1000" id="mycvs">當前瀏覽器不支持此控制項,請更換或更新瀏覽器</canvas>
<script type="text/javascript">
var a = document.getElementById("mycvs");
var can = a.getContext("2d");
var beginx = -(1 / 2 * Math.PI);//起始值
var r = 150;
var sidex = 1 * (Math.PI / 180);//增加值
var endx = beginx + 2 * Math.PI;//結束值
var bendx = beginx + 2 * Math.PI;
var aendx = beginx + Math.PI;
var tmx = beginx;//當前值
var t = 0;
var rends = function () {
if (tmx + sidex >= endx) {
tmx = beginx;
t = t + 1;
endx = endx - Math.PI;
if (t == 2) {//填充顏色並退出
can.save();
arcs(300, 300, r, beginx, aendx, true, "black");
arcs(300, 225, 75, beginx, aendx,null,"black");
arcs(300, 375, 75, beginx, aendx, true,"white");
arcs(300, 375, 20, beginx, bendx, null, "black");
arcs(300, 225, 20, beginx, bendx, null, "white");
return;
}
} else {
tmx += sidex;
}
can.clearRect(0, 0, 1000, 1000);//用clearRect()函數使圖像更加清晰 也造成一筆結束後上一筆清除了
can.lineWidth = 5;
if (t == 0)
{
can.beginPath();
can.arc(300, 300, r, beginx, tmx);
can.stroke();
} else if (t == 1) {
can.beginPath();
can.arc(300, 300, r, beginx, bendx);//所以在這裡我又重新畫了一遍外圓
can.arc(300, 225, 75, beginx, tmx);
can.arc(300, 375, 75, beginx, tmx, true);
can.stroke();
}
requestAnimationFrame(rends);//這個是動畫控制
};
function arcs(x,y,r,begin,end,f,color) {//圓心(x,y),半徑r,起始值begin,結束值end,方向f,填充顏色color
can.beginPath();
can.fillStyle = color;
can.arc(x, y, r, begin, end,f);
can.fill();
can.stroke();
}
rends();
</script>
</body>
</html>
這個代碼有點冗餘,初學者請多多指教謝謝。