js实现圆周
使用 Canvas 绘制圆周
在 HTML5 的 Canvas 中,可以通过 arc 方法绘制圆周。以下是示例代码:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.stroke();
arc 方法的参数依次为圆心 x 坐标、圆心 y 坐标、半径、起始角度(弧度)、结束角度(弧度)。2 * Math.PI 表示完整的圆周。
使用 SVG 绘制圆周
SVG 提供 circle 元素用于绘制圆周:
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" stroke="black" stroke-width="2" fill="none" />
</svg>
cx 和 cy 是圆心坐标,r 是半径,stroke 设置边框颜色,fill="none" 确保圆内部不填充。
使用 CSS 绘制圆周
通过 CSS 的 border-radius 属性可以实现圆形效果,但需结合伪元素或边框控制圆周:
.circle {
width: 100px;
height: 100px;
border: 2px solid black;
border-radius: 50%;
}
将 border-radius 设为 50%,并将宽高设为相同值,边框会呈现为圆周。
数学公式计算圆周点
通过参数方程计算圆周上的点坐标,可用于自定义渲染:
$$ x = r \cdot \cos(\theta) + x_0 \ y = r \cdot \sin(\theta) + y_0 $$
其中 $(x_0, y_0)$ 是圆心,$r$ 是半径,$\theta$ 为角度(弧度)。遍历 $\theta$ 从 0 到 $2\pi$ 可生成圆周上的所有点。
使用 D3.js 绘制圆周
D3.js 提供了便捷的 SVG 图形生成方法:

d3.select("body")
.append("svg")
.attr("width", 200)
.attr("height", 200)
.append("circle")
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 50)
.attr("stroke", "black")
.attr("fill", "none");
这种方法结合了 SVG 的声明式语法和 D3 的数据驱动特性。






