html:
<body onload="draw()">
<canvas id="c" width="210" height="210"></canvas>
<div>
<button onclick="rotate()">旋转</button>
<button onclick="cancelRotate()">停止旋转</button>
</div>
</body>
js:
const ctx = document.getElementById('c').getContext('2d');
const PI = Math.PI;
let rotateId = null; // 控制是否旋转
ctx.translate(105, 105); // 更改原点
function draw(r) {
ctx.clearRect(0, 0, 200, 200);
ctx.rotate(PI / 180);
// 最外侧大圆
ctx.beginPath(); // 注意:这里也需要加一个beginPath,不然会和draw()方法最后面的fill()连接起来多了一根线
ctx.arc(0, 0, 100, 0, PI * 2, true);
ctx.stroke();
// 左侧黑鱼
ctx.beginPath();
ctx.arc(0, 0, 100, -PI / 2, PI / 2, true);
ctx.fill();
// 上面中号黑圆 & 下面中号白色圆
ctx.beginPath();
ctx.arc(-1, -50, 50, -PI / 2, PI / 2, false);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = '#fff';
ctx.arc(1, 50, 50, -PI / 2, PI / 2, true);
ctx.fill();
// 上面白色鱼眼 & 下面黑色鱼眼
ctx.beginPath();
ctx.arc(0, -50, 5, 0, PI * 2, true);
ctx.fill();
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc(0, 50, 5, 0, PI * 2, true);
ctx.fill();
if (r) {
cancelAnimationFrame(rotateId);
rotateId = requestAnimationFrame(draw);
}
}
function rotate() {
draw(true);
}
function cancelRotate() {
cancelAnimationFrame(rotateId);
}
效果: