Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw an image with 2 points on a canvas

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.

like image 912
RaduGabor Avatar asked Feb 02 '26 12:02

RaduGabor


1 Answers

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);
like image 83
Dan Prince Avatar answered Feb 04 '26 00:02

Dan Prince



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!