js实现扇形
使用Canvas绘制扇形
在HTML5 Canvas中,可以通过arc()方法绘制扇形。以下是一个完整的示例代码:
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 定义圆心和半径
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 80;
// 开始绘制
ctx.beginPath();
ctx.moveTo(centerX, centerY); // 移动到圆心
ctx.arc(centerX, centerY, radius, 0, Math.PI / 2); // 绘制90度扇形
ctx.closePath(); // 闭合路径
// 设置样式
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
ctx.fill();
</script>
使用SVG绘制扇形
SVG提供了更简单的矢量图形绘制方式:

<svg width="200" height="200">
<path d="M100,100 L180,100 A80,80 0 0,1 100,180 Z" fill="blue" />
</svg>
解释SVG路径命令:
M100,100:移动到圆心(100,100)L180,100:画线到起始点(180,100)A80,80 0 0,1 100,180:绘制圆弧到(100,180)Z:闭合路径
使用CSS绘制扇形
纯CSS可以通过边框和旋转实现扇形效果:

<div class="fan"></div>
<style>
.fan {
width: 0;
height: 0;
border: 100px solid transparent;
border-top: 100px solid red;
border-radius: 100px;
transform: rotate(45deg);
}
</style>
动态生成扇形
以下函数可以生成任意角度和半径的扇形:
function drawSector(ctx, x, y, radius, startAngle, endAngle, color) {
ctx.beginPath();
ctx.moveTo(x, y);
ctx.arc(x, y, radius, startAngle, endAngle);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
}
// 使用示例
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
drawSector(ctx, 100, 100, 80, 0, Math.PI/3, 'green');
动画扇形效果
结合requestAnimationFrame实现动画效果:
let angle = 0;
function animate() {
const ctx = document.getElementById('canvas').getContext('2d');
ctx.clearRect(0, 0, 200, 200);
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.arc(100, 100, 80, 0, angle);
ctx.closePath();
ctx.fillStyle = 'orange';
ctx.fill();
angle += 0.01;
if(angle < Math.PI*2) {
requestAnimationFrame(animate);
}
}
animate();






