I am leaning to work with canvas objects. I have the following coordinates:
A: [x1,y1] B: [x2,y2]
and a width which is a number. I want to draw a rectangle on the canvas using these information. I know that the output can be two rectangles both sides of the AB.
One way can be to find two lines that are perpendicular to the AB and then from each point find another BC and AD points using width value.
Is there any better solutions for that?
Thanks
You don't need width if you know the vertices of both ends of a rectangle. Width and height can be obtained by subtracting the vertices of the square. Please refer to the following code.
const CANVAS_WIDTH = 400;
const CANVAS_HEIGHT = 300;
const canvas = Object.assign(document.createElement('canvas'), {width: CANVAS_WIDTH, height: CANVAS_HEIGHT});
const ctx = canvas.getContext('2d');
const A = [10, 30];
const B = [120, 250];
const drawRectByCorner = (ctx, corner1, corner2) => {
const [x1, y1] = corner1;
const [x2, y2] = corner2;
ctx.fillRect(x1, y1, x2 - x1, y2 - y1); // x, y, width, height
};
drawRectByCorner(ctx, A, B);