js实现画圆
使用 Canvas API 绘制圆形
Canvas API 是 HTML5 提供的绘图工具,通过 JavaScript 调用其方法实现图形绘制。以下是绘制圆形的基本代码示例:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2); // x坐标, y坐标, 半径, 起始角, 结束角
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
使用 SVG 动态创建圆形
SVG 是矢量图形标准,可通过 DOM 操作动态生成圆形元素:
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");
svg.appendChild(circle);
document.body.appendChild(svg);
使用 CSS 绘制圆形
通过 CSS 的 border-radius 属性可以实现纯前端圆形绘制:
const div = document.createElement('div');
div.style.width = '100px';
div.style.height = '100px';
div.style.borderRadius = '50%';
div.style.backgroundColor = 'green';
document.body.appendChild(div);
使用 WebGL 绘制圆形
对于高性能图形需求,可以使用 WebGL 进行绘制:
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
// 顶点着色器
const vsSource = `
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}`;
// 片段着色器
const fsSource = `
precision mediump float;
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}`;
// 创建着色器程序
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
const positions = [];
for (let i = 0; i < 360; i++) {
const angle = (i * Math.PI) / 180;
positions.push(Math.cos(angle) * 0.5, Math.sin(angle) * 0.5);
}
// 创建缓冲区并绘制
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
gl.drawArrays(gl.TRIANGLE_FAN, 0, positions.length / 2);
使用 D3.js 绘制圆形
数据可视化库 D3.js 提供便捷的圆形绘制方法:

import * as d3 from 'd3';
const svg = d3.select("body").append("svg")
.attr("width", 200)
.attr("height", 200);
svg.append("circle")
.attr("cx", 100)
.attr("cy", 100)
.attr("r", 50)
.style("fill", "purple");
每种方法适用于不同场景:Canvas 适合动态绘图,SVG 适合可缩放图形,CSS 最简单,WebGL 适合复杂3D图形,D3.js 适合数据可视化。根据项目需求选择合适的技术方案。






