Canvas - Rotate line

8.4k Views Asked by At

I am new to Canvas and I need to do some things I cannot find answer on google ...

Suppose I have a line w/ starting & ending points. I need to rotate this line around the starting point.

Here is the jsfiddle : http://jsfiddle.net/0cc6h833/1/

var cd;
var ctx2;
var startPoint;
var endPoint;
        function init(){
            cd= document.getElementById("canvas2");
            cd.width=500;
            cd.height=500;

            ctx2=cd.getContext("2d");
        }


        function draw(){
            startPoint={ x:200, y:200};
            endPoint={ x:startPoint.x+100, y:startPoint.y+100};

            ctx2.beginPath();
                ctx2.setLineDash([1,2]);
                ctx2.moveTo(startPoint.x,startPoint.y);
                ctx2.lineTo(endPoint.x,endPoint.y);
                ctx2.stroke();
                ctx2.closePath();            
        }

init();
draw();

Also I am open to use any of Canvas Library. I know that will be simpler but I don't know which one to choose

1

There are 1 best solutions below

1
On BEST ANSWER

You can use transformations to rotate a line or any shape drawn to canvas. To rotate:

  • Translate to pivot point, ie. point of rotation
  • Apply rotation transform
  • Translate back
  • Draw shape

In your case, if we say rotate around the middle of the line:

var cd;
var ctx2;
var startPoint;
var endPoint;
var midPoint;

function init() {
  cd = document.getElementById("canvas2");
  cd.width = 500;
  cd.height = 500;

  ctx2 = cd.getContext("2d");
}


function draw() {
  startPoint = {
    x: 200,
    y: 200
  };
  endPoint = {
    x: startPoint.x + 100,
    y: startPoint.y + 100
  };

  ctx2.beginPath();
  ctx2.setLineDash([1, 2]);
  
  // rotate around center - find mid-point using lerp
  midPoint = {
    x: startPoint.x + (endPoint.x - startPoint.x) * 0.5,
    y: startPoint.y + (endPoint.y - startPoint.y) * 0.5
  };
  
  // translate to midpoint
  ctx2.translate(midPoint.x, midPoint.y);
  
  // rotate some angle (radians)
  ctx2.rotate(0.25 * Math.PI);  // = 45°
  
  // translate back
  ctx2.translate(-midPoint.x, -midPoint.y);

  // draw line
  ctx2.moveTo(startPoint.x, startPoint.y);
  ctx2.lineTo(endPoint.x, endPoint.y);
  ctx2.stroke();
  ctx2.closePath();
  
  // reset transforms
  ctx2.setTransform(1,0,0,1,0,0);
}

init();
draw();
<canvas id="canvas2" width="500" height="500" style="border:1px solid #000000;">
</canvas>

That being said, if you need to interact with the line then transformation can appear confusing because mouse positions do not inverse the transformation and will end up a different place than what you expect them.

For this reason you could use manual transformation so you know the exact location of the line ends after being transformed (with the built-in transformation you operate on the original position).

For this, please see this answer for an approach on that part.