Practical example: curved arrows

Practical example: use quadratics for drawing curved arrows

 

We propose a useful function for drawing curved arrows. The code is a modified version of one that has been proposed by several contributors to this thread at StackOverflow.

Source code of the function that draws a curved arrow:

  1. function drawCurvedArrow(startPointX, startPointY,
  2.                          endPointX, endPointY,
  3.                          quadPointX, quadPointY,
  4.                          lineWidth,
  5.                          arrowWidth,
  6.                          color) {
  7.     // BEST PRACTICE: the function changes color and lineWidth -> save context!
  8.     ctx.save();
  9.     ctx.strokeStyle = color;
  10.     ctx.lineWidth = lineWidth;
  11.  
  12.     // angle of the end tangeant, useful for drawing the arrow head
  13.     var arrowAngle = Math.atan2(quadPointX endPointX, quadPointY endPointY) + Math.PI;
  14.  
  15.     // start a new path
  16.     ctx.beginPath();
  17.     // Body of the arrow
  18.     ctx.moveTo(startPointX, startPointY);
  19.     ctx.quadraticCurveTo(quadPointX, quadPointY, endPointX, endPointY);
  20.     // Head of the arrow
  21.     ctx.moveTo(endPointX (arrowWidth * Math.sin(arrowAngle Math.PI / 6)),
  22.                endPointY (arrowWidth * Math.cos(arrowAngle Math.PI / 6)));
  23.  
  24.     ctx.lineTo(endPointX, endPointY);
  25.  
  26.     ctx.lineTo(endPointX (arrowWidth * Math.sin(arrowAngle + Math.PI / 6)),
  27.                endPointY (arrowWidth * Math.cos(arrowAngle + Math.PI / 6)));
  28.  
  29.     ctx.stroke();
  30.     ctx.closePath();
  31.     // BEST PRACTICE -> restore the context as we saved it at the beginning
  32.     // of the function
  33.     ctx.restore();
  34. }

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s