js实现圆周
使用 Canvas 绘制圆周
在 JavaScript 中绘制圆周可以通过 HTML5 的 <canvas> 元素实现。以下是具体实现方法:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 设置圆心坐标和半径
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 50;
// 绘制圆周
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.stroke();
使用 SVG 绘制圆周
SVG 是另一种在网页上绘制圆周的方式,适合矢量图形:
const svg = document.getElementById('mySvg');
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
// 设置圆心坐标和半径
circle.setAttribute('cx', '100');
circle.setAttribute('cy', '100');
circle.setAttribute('r', '50');
circle.setAttribute('stroke', 'green');
circle.setAttribute('stroke-width', '2');
circle.setAttribute('fill', 'none');
svg.appendChild(circle);
计算圆周上的点坐标
如果需要动态计算圆周上的点坐标,可以使用三角函数:
function getPointOnCircle(centerX, centerY, radius, angle) {
const x = centerX + radius * Math.cos(angle);
const y = centerY + radius * Math.sin(angle);
return { x, y };
}
// 示例:获取圆周上 45 度角的点
const point = getPointOnCircle(100, 100, 50, Math.PI / 4);
console.log(point); // 输出坐标
动画圆周效果
为圆周添加动画效果,可以使用 requestAnimationFrame:

let angle = 0;
function animate() {
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(150, 150, 50, 0, angle % (2 * Math.PI));
ctx.strokeStyle = 'red';
ctx.stroke();
angle += 0.05;
requestAnimationFrame(animate);
}
animate();
以上方法涵盖了从静态绘制到动态动画的圆周实现方式,可以根据需求选择适合的技术方案。






