Reputation: 115
I have to points (x1, x2, y1, y2). How can I draw an image (it's like a rectangle of width 10 and height 100) on a canvas with starting point x1, y1 and rotation degree determined by slope of the line between that two points?
It's like I want to overlap this line with an image:
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
And I tried like this:
slope = (y2 - y1) / (x2 - x1)
ctx.save();
ctx.rotate(-Math.atan(slope));
ctx.drawImage(image, x1, y1);
ctx.restore();
But with no success.
Thank you.
Upvotes: 3
Views: 953
Reputation: 30009
ctx.rotate
will rotate the context around the canvas origin.
In order to rotate around the corner of the shape, you'll need to translate the context to that point.
var slope = (pt.y1 - pt.y2) / (pt.x1 - pt.x2);
ctx.save();
ctx.translate(pt.x1, pt.y1);
ctx.rotate(Math.atan(slope));
// we've already moved to here, so we can draw at 0, 0
ctx.drawImage(image, 0, 0);
ctx.restore();
This only works for positive slopes. It's possible to also account for negative slopes by inverting the rotation if the slope is negative.
var slopeIsNegative = slope < 0;
var offsetAngle = slopeIsNegative ? Math.PI : 0;
ctx.rotate(Math.atan(slope) + offsetAngle);
Upvotes: 1