jonobr1 / two.js

A renderer agnostic two-dimensional drawing api for the web.
https://two.js.org
MIT License
8.31k stars 455 forks source link

How to draw double arrowed line ??? [Question] #545

Closed ayush11-11 closed 3 years ago

ayush11-11 commented 3 years ago

To Draw Double arrowed Line I have to use below code-

two.makeArrow(fromx, fromy,tox,toy,r); two.makeArrow(tox,toy,fromx,fromy,r);

image

It produces image like this but because of overlapping of two lines after converting it into base 64 and decoding it I found skewed image. Did we have any method in two.js to draw double arrowed line to resolve this issue???

jonobr1 commented 3 years ago

Thanks for the message. There isn't a way to do this as one element at the moment, but if you look at the underlying code of makeArrow you could construct your own make method like so:

function makeDoubleSidedArrow(x1, y1, x2, y2, size) {

  var headlen = typeof size === 'number' ? size : 10;

  var angle = Math.atan2(y2 - y1, x2 - x1);

  var vertices = [

    new Two.Anchor(x1, y1, undefined, undefined, undefined, undefined, Two.Commands.move),
    new Two.Anchor(
      x1 - headlen * Math.cos(angle - 3 * Math.PI / 4),
      y1 - headlen * Math.sin(angle - 3 * Math.PI / 4),
      undefined, undefined, undefined, undefined, Two.Commands.line
    ),

    new Two.Anchor(x1, y1, undefined, undefined, undefined, undefined, Two.Commands.move),
    new Two.Anchor(
      x1 - headlen * Math.cos(angle + 3 * Math.PI / 4),
      y1 - headlen * Math.sin(angle + 3 * Math.PI / 4),
      undefined, undefined, undefined, undefined, Two.Commands.line
    ),

    //

    new Two.Anchor(x1, y1, undefined, undefined, undefined, undefined, Two.Commands.move),

    //

    new Two.Anchor(x2, y2, undefined, undefined, undefined, undefined, Two.Commands.line),
    new Two.Anchor(
      x2 - headlen * Math.cos(angle - Math.PI / 4),
      y2 - headlen * Math.sin(angle - Math.PI / 4),
      undefined, undefined, undefined, undefined, Two.Commands.line
    ),

    new Two.Anchor(x2, y2, undefined, undefined, undefined, undefined, Two.Commands.move),
    new Two.Anchor(
      x2 - headlen * Math.cos(angle + Math.PI / 4),
      y2 - headlen * Math.sin(angle + Math.PI / 4),
      undefined, undefined, undefined, undefined, Two.Commands.line
    )

  ];

  var path = new Two.Path(vertices, false, false, true);
  path.noFill();
  path.cap = 'round';
  path.join = 'round';

  return path;

}

Fiddle link here.