将弧分成几部分

时间:2017-04-30 10:12:15

标签: javascript html5-canvas

我正在尝试构建一个日历,并希望将此弧分为12个部分,我可以在以后单独操作(如饼图),但我不明白我是如何实现这一目标的。

此外,绘画应该从12点开始。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var y = 350;
var x = 300;

var radius = 200;
var lineWidth = 1;


//Draw January
for (var i = 0; i <= 31; i++) {
    ctx.beginPath();
    ctx.arc(x, y, radius, -Math.PI/2, Math.PI/12, false);
    ctx.stroke();
}

//Draw February
for (var i = 0; i <= 31; i++) {
    ctx.beginPath();
    ctx.arc(x, y, radius, -Math.PI/2, Math.PI/12, false);
    ctx.stroke();
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body style="background-color: #fff;">

    <canvas id="canvas" width="800" height="600" style="border: 1px solid black;">
    </canvas>

    <script src="script.js"></script>

  </body>
</html>

1 个答案:

答案 0 :(得分:1)

您需要以弧度指定正确的起始和结束角度。从12点钟开始的整圈以start = -Math.PI / 2的角度开始,以start + 2 * Math.PI结束。要指定整圆的1/12,需要除以12:

&#13;
&#13;
// Draw the i/12th arc segment starting at 12 o'clock:
function drawOneTwelfthArc(ctx, x, y, radius, i) {
  var start = Math.PI / 6 * i - Math.PI / 2;
  var end = start + Math.PI / 6;
  ctx.beginPath();
  ctx.arc(x, y, radius, start, end);
  ctx.stroke();
}

// Example:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

drawOneTwelfthArc(ctx, 50, 50, 30, 0);
drawOneTwelfthArc(ctx, 50, 50, 40, 1);
drawOneTwelfthArc(ctx, 50, 50, 50, 2);
drawOneTwelfthArc(ctx, 50, 50, 60, 3);
drawOneTwelfthArc(ctx, 50, 50, 70, 4);
drawOneTwelfthArc(ctx, 50, 50, 80, 5);
&#13;
<canvas id="canvas">
&#13;
&#13;
&#13;