Mouse position on canvas

The code below is colored correctly, but it draws the wrong coordinates. He should draw a place where the mouse is. I could not find my mistake. Thank.

JSFIDDLE

container.mousedown(function(e) { var parentOffset = $(this).offset(); var x = e.pageX - parentOffset.left; var y = e.pageY - parentOffset.top; context_temp.beginPath(); context_temp.moveTo(x, y); started = true; }); container.mousemove(function(e) { var parentOffset = $(this).offset(); var x = e.pageX - parentOffset.left; var y = e.pageY - parentOffset.top; if (started) { context_temp.lineTo(x, y); context_temp.stroke(); } }); container.mouseup(function(e) { var parentOffset = $(this).offset(); var x = e.pageX - parentOffset.left; var y = e.pageY - parentOffset.top; if (started) { container.mousemove(x, y); started = false; update(); } }); 
+9
javascript jquery html canvas
Jan 02
source share
2 answers

You set the width and height of the canvas in CSS. It just stretches the canvas just like the image.

The effect is drawn in the wrong place.

Instead, you need to set the canvas dimensions on the tag itself:

 <canvas width="400" height="400"></canvas> 
+5
Jan 02 '14 at
source share

A <canvas> has its own width and height , which not only determine its physical size (except CSS), but also its logical size (the number of rows / columns of pixels on its drawing surface). When CSS resizes, the canvas stretches to fit, but does not change its logical size. In principle, pixels are also stretched, so the logical and physical coordinates no longer match.

To fix the problem, you can either do the math according to the coordinate backups, or use only the canvas’s own width / height for their size, or set the width and height properties of the canvas after the fact matches the width and height set by CSS.

+3
Jan 02 '14 at
source share



All Articles