coure2011
coure2011

Reputation: 42404

rotating an arrow in canvas

I want to rotate the arrow to any given angle. What i need to add/modify so that it can be rotated to any angle. Currently its on 180 degree.

function drawArrowAtAngle(cx,cy,angle,context){
  context.save();
  context.beginPath();
  context.lineWidth = 1;
  context.strokeStyle = '#aaa';
  context.moveTo(cx+25,cx-2);
  context.lineTo(cx-55,cx-2);
  context.lineTo(cx-58,cx);
  context.lineTo(cx-55,cx+2);
  context.lineTo(cx+25,cx+2);
  context.lineTo(cx+25,cx-2);  
  context.stroke();
  context.closePath();
  context.restore();

 }

Upvotes: 1

Views: 1876

Answers (1)

brainjam
brainjam

Reputation: 19005

Assuming that you want the center of rotation to be (cx,cx), insert the following three lines after the context.save(); statement.

  context.translate(cx,cx) ;
  context.rotate(angle) ;
  context.translate(-cx,-cx) ;

This will cause the arrow to be rotated clockwise by angle (in radians).

You use (cx,cx) in your code to anchor the arrow. If you really mean (cx,cy), then adjust the above snippet accordingly.

Upvotes: 4

Related Questions