Draw a square from cursor center

Viewed 213

Currently I have a canvas where you can draw a square with your cursor like paint.net. As you drag your cursor it will create a square starting from the left corner. I wish for it to start at the center of the square instead. Is it possible to achieve this with rect ?

The code below draws a square starting from the left corner where mouseCoords is the starting point where your cursor started dragging and currentMouse is the location where you have dragged to.

//create rectangle starting from left corner
canvas.getContext('2d').rect(
  mouseCoords.x,
  mouseCoords.y,
  currentMouse.x - mouseCoords.x,
  currentMouse.y - mouseCoords.y
);
2 Answers

If mouseCoords.x and mouseCoords.y are the center, then currentMouse.x - mouseCoords.x and currentMouse.y - mouseCoords.y will be half the width and half the height, respectively. With that in mind it should be straightforward; the x coordinate will be mouseCoords.x - (currentMouse.x - mouseCoords.x) which is 2 * mouseCoords.x - currentMouse.x, the same goes for the y coordinate:

canvas.getContext('2d').rect(
  2 * mouseCoords.x - currentMouse.x,
  2 * mouseCoords.y - currentMouse.y,
  2 * (currentMouse.x - mouseCoords.x),
  2 * (currentMouse.y - mouseCoords.y)
);

It's more clearer if you use variables that describe the values:

let halfWidth = currentMouse.x - mouseCoords.x;
let halfHeight = currentMouse.y - mouseCoords.y;

canvas.getContext('2d').rect(
  mouseCoords.x - halfWidth,
  mouseCoords.y - halfHeight,
  2 * halfWidth,
  2 * halfHeight
);

I found the solution. I made a mistake where I forgot to multiply the width and height.

context.rect(
  mouseCoords.x - (currentMouse.x - mouseCoords.x),
  mouseCoords.y - (currentMouse.y - mouseCoords.y),
  (currentMouse.x - mouseCoords.x) * 2,
  (currentMouse.y - mouseCoords.y) * 2
);
Related