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); // x, y, 半径, 起始角, 结束角
ctx.fillStyle = 'blue'; // 填充颜色
ctx.fill(); // 填充圆形
ctx.strokeStyle = 'black'; // 边框颜色
ctx.lineWidth = 2; // 边框宽度
ctx.stroke(); // 绘制边框
使用SVG画圆
SVG是一种矢量图形格式,可以直接在HTML中使用,也可以通过JavaScript动态创建。

// 创建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", "red");
circle.setAttribute("stroke", "black");
circle.setAttribute("stroke-width", "2");
// 添加到SVG和DOM中
svg.appendChild(circle);
document.body.appendChild(svg);
使用CSS画圆
CSS可以通过border-radius属性创建圆形元素,结合JavaScript可以动态控制样式。
// 创建div元素
const circleDiv = document.createElement('div');
circleDiv.style.width = '100px';
circleDiv.style.height = '100px';
circleDiv.style.borderRadius = '50%';
circleDiv.style.backgroundColor = 'green';
circleDiv.style.border = '2px solid black';
// 添加到DOM中
document.body.appendChild(circleDiv);
使用D3.js画圆
D3.js是一个强大的数据可视化库,可以方便地绘制各种图形。

// 创建SVG容器
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)
.attr("fill", "purple")
.attr("stroke", "black")
.attr("stroke-width", 2);
使用Three.js画3D圆
Three.js是一个3D图形库,可以创建3D圆形或球体。
// 创建场景、相机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(200, 200);
document.body.appendChild(renderer.domElement);
// 创建球体几何体
const geometry = new THREE.SphereGeometry(5, 32, 32);
const material = new THREE.MeshBasicMaterial({ color: 0xffff00 });
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);
camera.position.z = 10;
// 渲染场景
function animate() {
requestAnimationFrame(animate);
sphere.rotation.x += 0.01;
sphere.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
使用P5.js画圆
P5.js是一个创意编程库,简化了绘图过程。
function setup() {
createCanvas(200, 200);
}
function draw() {
background(220);
fill(255, 0, 0);
stroke(0);
strokeWeight(2);
ellipse(100, 100, 100, 100);
}






