学位文本需要在javascript中对齐

时间:2014-02-11 09:55:24

标签: javascript jquery html5 canvas html5-canvas

在这个小提琴中,四个粉红色点可移动[它可拖动]。它形成任何多边形形状。在单击绘图按钮时,它会绘制每个角落角度。这没关系。但是我需要一个弧形前面的学位文本。

现有的:

enter image description here

我需要这样:

enter image description here

    ctx.save();
    ctx.beginPath();
    ctx.moveTo(b1, b2);

    ctx.arc(b1, b2, 20, ax1, ax2, !isInside);
    console.log(ax1, ax2);
    ctx.closePath();
    ctx.fillStyle = "red";
    ctx.globalAlpha = 0.25;
    ctx.fill();
    ctx.restore();

    ctx.fillStyle = "black";
    ctx.fillText((isInside ? a : 360 - a) + '°', b1 + 15, b2);

它可能。提前谢谢。

请参阅此小提琴:http://jsfiddle.net/yn4yg/1/

3 个答案:

答案 0 :(得分:3)

您的代码包含回答问题所需的相同数学内容???!

ctx.arc(b1, b2, 20, ax1, ax2, !isInside);
  • 将角度ax2,ax1平分。

  • 如果扫描是逆时针方向,则添加PI(必要时在2 * PI内标准化)。

  • 可选择从二等分角度中减去一点,以说明文本的长度。

  • 计算b1 / b2处在二等分角处至少延伸20个像素的点。

答案 1 :(得分:3)

这应该做你想做的事:http://jsfiddle.net/natalieperna/6F3p7/1/

  1. 找到ax1ax2
  2. 的二分
  3. 检查它是否指向多边形内部(与现有isInside var不同),如果不是,则添加PI
  4. 设置文本位置30向下二分角
  5. 将文本位置5向左移动以考虑标签的长度

答案 2 :(得分:1)

这可以让你接近你想要的东西:

// Get the starting and ending points of the arc
var angle = (isInside ? a : 360 - a);
var s_x = b1+20*Math.cos(ax1);
var s_y = b2+20*Math.sin(ax1);
var e_x = b1+20*Math.cos(ax2);
var e_y = b2+20*Math.sin(ax2);

ctx.fillText(angle + '°', ((s_x+e_x)/2), ((s_y+e_y)/2));

这是工作jsFiddle