如何在 Canvas 中绘制扇形

如题所述

<canvas id="canvas" width="150" height="150"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
function DrawSector(canvas_tag,start_angle,angle,radius,fill,anticlockwise){
var centerPoint = {x:75,y:75};
start_angle = start_angle || 0;
if (canvas_tag.getContext){
//开始绘制路径
ctx = canvas_tag.getContext("2d");
ctx.beginPath();
//画出弧线
ctx.arc(centerPoint.x,centerPoint.y,radius,start_angle,angle,anticlockwise);
//画出结束半径
ctx.lineTo(centerPoint.x,centerPoint.y);
//如果需要填充就填充,不需要就算了
if (fill) {
ctx.fill();
}else{
ctx.closePath();
ctx.stroke();
}
} else {
alert('You need Safari or Firefox 1.5+ to see this demo.');
}
}
//画一个起始角度为45度,结束角度为90度,绘图方向顺时针的填充扇形
DrawSector(canvas,Math.PI/4,Math.PI/2,50,true,false);
//画一个起始角度为-90度,结束角度为-135度,绘图方向逆时针的未填充扇形
DrawSector(canvas,-Math.PI/2,-Math.PI*3/4,50,false,true);
</script>
温馨提示:答案为网友推荐,仅供参考
相似回答