http://www.asifslab.com/reveal.js-master/Why%20does%20wind%20feel%20cold.html#/4 Why doesn't the drawing canvas work properly? The line drawn is away from the point clicked. However, if I use the canvas out of reveal.js it works perfectly. http://codepen.io/anon/pen/eEaKh Also when the erase function is run, it leaves a white border outside. How do I fix these problems?
Asked
Active
Viewed 721 times
0
-
The first link is dead. Please update it and add the relevant source code here. – Martin Thoma Apr 06 '14 at 08:02
3 Answers
0
just change e.pageX
to e.clientX
and e.pageY
to e.clientY
because in your codepen account
canvas origin and page origin is almost at same place but in other it is not.

singhiskng
- 511
- 1
- 5
- 15
0
To calculate the mouse position you need to subtract the position of the canvas:
Here is one way of doing this (inside the event handler):
var rect = canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
Now your x
and y
will be relative to canvas.
0
Here's a copy/pasta of a small part of my paint app. Notice I'm using offsets of the canvas in my calculations. I also have a zoom function that scales the canvas, so taking into account that I added it to the calculation of the mouse cursor.
$('canvas').mousemove(function(e) {
// x and y are globals, x inits to null, mousedown sets x, mouseup returns x to null
if (x==null) return;
x = (100/$('#zoom').val())*(e.pageX - $(this).offset().left);
y = (100/$('#zoom').val())*(e.pageY - $(this).offset().top);
$('#debug').html(x+', '+y); // constantly update (x,y) position in a fixed div during debugging
});

MaKR
- 1,882
- 2
- 17
- 29