任何人都可以告诉我如何在javascript中以任意角度从一个项目到另一个项目绘制曲线?

时间:2010-11-05 11:14:13

标签: javascript html5 canvas drawing

仅仅是为了上下文,我使用的是html5,css和jquery。

我希望能够在网页上的两个元素之间绘制带箭头的曲线。我几乎得到了它,但是无法绕过数学来画出箭头。可能只是操纵了我的画布小部件。

这是我正在使用的javascript。它当然感觉还有很长的路要走,但除了那些讨厌的箭头外,它似乎完成了工作。

'影响'变量是稍微改变线条,这样如果有多条线条,它们会一个接一个地显示。

  var start = $('#firstobject');
  var last = $('#lastobject');
  var stpos = start.position();
  var lastpos = last.position();
  var influence = Math.random*20+5;
  var maxx = Math.max(stpos.left,lastpos.left);
  var minx = Math.min(stpos.left,lastpos.left);
  var maxy = Math.max(stpos.top,lastpos.top);
  var miny = Math.min(stpos.top,lastpos.top);
  var w = maxx - minx;
  var h = maxy - miny;
  var cname = "samplename";
  var cpad = 30;
  var cstr = "<canvas id='"+cname+"' class='huntgroupcanvas' style='z-index:2;position:absolute;left:"+(0+minx-cpad)+"px;top:"+(0+miny-cpad)+"px;' id='"+cname+"' width="+(2*cpad+w)+" height="+(2*cpad+h)+"></canvas>"
  start.before(cstr);
  var canvas = document.getElementById(cname);
  var ctx = canvas.getContext("2d");
  var dx = stpos.left - lastpos.left;
  var dy = stpos.top - lastpos.top;
  var dir = dy/dx;
  var sx,sy,ex,ey;
  if (dir<0) {
    ex=w+cpad;
    ey=cpad;
    sx=cpad;
    sy=h+cpad;
  } else {
    ex=w+cpad;
    ey=h+cpad;
    sx=cpad;
    sy=cpad;
  }

  ctx.lineWidth=1;
  ctx.strokeStyle = '#000';
  ctx.beginPath();
  ctx.moveTo(sx,sy);
  ctx.quadraticCurveTo(((w/2)-(h/2))+cpad-influence,((h/2)-(w/2))+cpad,ex,ey);
  ctx.stroke();
  if (st==i-1) {
    first=0;
    ctx.beginPath();
    if (dx<0) {
      ctx.arc(sx,sy,6,0,Math.PI*2,0);
    } else {
      ctx.arc(ex,ey,6,0,Math.PI*2,0);
    }
    ctx.stroke();
  }

 /* Here's where I've been trying to draw the arrowheads.
  * I know that I can get the slope of the line like so:
    var m = (y2-y1)/(x2-x1);
  * I know I can get the angle in radians as
    var angle=Math.atan(m);
  * I'm trying to use rotation to draw the arrowhead
 */
      ctx.save();
      ctx.beginPath();
      angle = Math.atan(dir);
      if (dx<0) {
        sx=ex;
        sy=ey;
        angle = Math.atan(-dir);
      }
      ctx.moveTo(sx,sy);
      ctx.translate(sx,sy);
      ctx.rotate(angle - 0.05);
      ctx.lineTo(20,0);
      ctx.rotate(angle + 0.05);
      ctx.lineTo(20,0);
      ctx.closePath();
      ctx.fill();
      ctx.restore();

1 个答案:

答案 0 :(得分:0)

这是很多要阅读的代码,但是在生成箭头的角度时,你似乎搞乱了三角函数。看看atan2函数,它需要一个2D矢量并将其转换为它的角度。所以你想要使用angle=Math.atan2(dy,dx)