2

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?

Community
  • 1
  • 1
Joachim
  • 245
  • 2
  • 10

1 Answers1

1

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);
Matt Mokary
  • 717
  • 6
  • 13
  • Thanks, I tried that on the example application and it worked fine. One more small question, please: In his example, there is code like this - `context.translate( -( mousex / scale + originx - mousex / ( scale * zoom ) ) );`. I don't understand this part: `- mousex / ( scale * zoom ) `. What does that do? – Joachim Feb 07 '17 at 19:49
  • `scale * zoom` is the new scale factor. That example divides the mouse coordinate by this new scale and subtracts it from the mouse coordinate divided by the old scale, effectively recording in `originx` and `originy` *by what magnitude the origin has changed* as a result of the scale. – Matt Mokary Feb 07 '17 at 20:35
  • Thank you so much! – Joachim Feb 08 '17 at 09:32