2
votes

I'm working on an HTML5 application which renders shapes on canvas. The shapes are drawn by the user, using free drawing.

I implemented zooming, thanks to this answer: https://stackoverflow.com/a/6776341/

However, once the canvas is zoomed, when user continues to draw, the lines appear with offset. The question is how to translate the points so the lines to be drawn under the cursor again?

1

1 Answers

1
votes

When you get mouse coordinates from the <canvas> element, they are relative to the element's height and width as far as the DOM is concerned. They won't change based on how you've scaled the canvas's context. In order to get the coordinates of the canvas under the cursor, you have to transform them to match the canvas's current transform.

// mouse event coordinates
var mouseX;
var mouseY;

// current canvas transforms
var originX;
var originY;
var scale;

// adjust mouse coordinates with canvas context's transforms
var canvasX = mouseX / scale + originX;
var canvasY = mouseY / scale + originY;

// should draw a rectangle with the cursor being directly in the center
context.fillRect(canvasX - 10, canvasY - 10, 20, 20);