Reputation: 1204
I have a script for drawing on a canvas. I am adding an event listener on mousedown and remove the listener on mouse up. It is working on Chrome but not on Firefox.
the code is like this:
$('#sketchCanvas').on("mousedown", function () {
$('#sketchCanvas').on("mousemove", drawSketch);
});
$('#sketchCanvas').on("mouseup", function () {
$('#sketchCanvas').off("mousemove", drawSketch);
});
drawSketch = function (event) {
$("#mouseXY").text("x: "+event.offsetX + " y: " + event.offsetY);
};
.redborder {
border:solid 1px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="sketchCanvas" width="200" height="200" class="redborder"></canvas>
<br/>
<span id="mouseXY" class="redborder">mouse coordinates</span>
here is a jsfiddle example of the same code: http://jsfiddle.net/womvLmk5/14/
Any ideas why this is happening? what is wrong on the above code?
thanks!
Upvotes: 0
Views: 803
Reputation: 14937
try like so:
drawSketch = function (event) {
var eTgtPos = $(event.target).offset(),
x = (event.offsetX || event.clientX - eTgtPos.left),
y = (event.offsetY || event.clientY - eTgtPos.top);
$("#mouseXY").text("x: "+x + " y: " + y);
};
See this fiddle
The mouse event object is defined in Firefox, just offsetX
and offsetY
are not defined within that object.
I also changed this bit to handle the mouse leaving the sketch area:
$('#sketchCanvas').on("mouseup mouseleave", function () {
$('#sketchCanvas').off("mousemove", drawSketch);
});
That makes it so the event turns off even if the mouseup event happens outside the canvas
HTH
Upvotes: 1