Javascript画布弧不是根据角度绘制的

时间:2015-10-08 12:49:51

标签: javascript

嗨我在绘制图表时遇到问题。情况是剩余天数,我需要画画和弧

var eAngle          = tax * 0.0172;

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

ctx.beginPath();

ctx.arc(100,100,70,1.5 , Math.PI * eAngle, true);

ctx.stroke();

另外,我如何在圆弧的中间写一些文字。

2 个答案:

答案 0 :(得分:1)

我已经调整了一点代码。首先,我们需要知道你一年中每天的角度。我要说这将是一个完整的圆圈(Math.PI * 2)除以365(或366当它的一个那些 - 年)。然后是正确理解弧函数的问题:

arc(x, y, radius, angle (0 = x-axis to the right), end angle (starting x-axis where 1 radian is a full circle), counterclockwise (true is counterclockwise drawing from start until the end angle, and false or ommitting is the regular clockwise angle);

最后,这将有效:

context.arc(100, 100, 50, -Math.PI / 2, -Math.PI / 2 + day * (Math.PI * 2 / 365), false);

其中,依次为:x-position,y-position,radius,-90度(从y轴而不是x开始),当你输入一天加上偏移时输出的是什么以前的论点。

要在此基础上绘制文字,您只需使用画布fillText功能。



var dayArc = Math.PI * 2 / 365;
var dayN   = 0;
var offset = -Math.PI / 2;

var canvas = document.getElementById("tax")
var context = canvas.getContext('2d');

setInterval(function(){
  dayN = dayN > 364 ? 0 : dayN+1;
  canvas.width = 500;
  context.beginPath();
  context.arc(100, 100, 50, offset, offset  + dayN * dayArc, false);
  context.stroke();

  context.textAlign = 'center';
  context.font = "24px 'Helvetica Neue', sans-serif";
  context.fillText((365-dayN) + '/365', 100, 110);
}, 1000 / 60);

<canvas id="tax" widht="500" height="500"></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

好。因此,我会将计算分开,以便更清楚地了解正在发生的事情。我们知道整圆是Math.PI * 2弧度。所以我们将它分开。

由于我们只需要一小部分圆圈,表示一年中的天数,我们会保留一个单独的变量,例如fractionOfCircle,然后将它们相乘以得到最终结果。

var fractionOfCircle = days / 365;

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

ctx.beginPath();

ctx.arc(100, 100, 70, 1.5, Math.PI * 2 * fractionOfCircle, true);

ctx.stroke();

要在圆圈中放置文字,我的第一种方法是覆盖HTML元素,例如div,并相应地定位文字。