js实现画圆
使用Canvas API画圆
Canvas API是HTML5提供的绘图工具,通过JavaScript调用可以绘制圆形。
// 获取Canvas元素
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制圆形
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
arc()方法参数说明:
- 前两个参数表示圆心坐标(x,y)
- 第三个参数是半径
- 后两个参数是起始角度和结束角度(以弧度计)
使用SVG绘制圆形
通过创建SVG元素实现矢量图形绘制,适合需要缩放保持清晰度的场景。

// 创建SVG元素
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "200");
svg.setAttribute("height", "200");
// 创建圆形
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("fill", "blue");
// 添加到DOM
svg.appendChild(circle);
document.body.appendChild(svg);
使用CSS绘制圆形
纯CSS方案适合简单的圆形显示需求,无需JavaScript绘图操作。
// 创建div元素
const circle = document.createElement('div');
circle.style.width = '100px';
circle.style.height = '100px';
circle.style.borderRadius = '50%';
circle.style.backgroundColor = 'green';
// 添加到页面
document.body.appendChild(circle);
使用D3.js库绘制
数据可视化库D3.js提供更高级的图形绘制功能。

// 使用D3创建SVG圆形
d3.select("body")
.append("svg")
.attr("width", 200)
.attr("height", 200)
.append("circle")
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 50)
.style("fill", "purple");
性能优化建议
Canvas方案适合动态图形和游戏开发,SVG更适合需要交互的矢量图形。静态简单图形可考虑CSS方案,复杂数据可视化推荐使用D3等专业库。
绘制大量圆形时,应注意:
- Canvas需要手动管理重绘
- SVG要注意DOM节点数量
- 使用requestAnimationFrame实现动画流畅性






