0

I have created a jquery widget that allows me to attach it to a canvas and record the drawings the user creates.

I have a problem with Firefox where the event fired by jQuery does not work; but the native javascript event is working.

A JSFiddle of the problem: http://jsfiddle.net/sk6N5/8/

I am able to draw in canvas1 but not in canvas2. I don't know why the drawing is a bit off; but in my own widget it's working as expected(so that doesn't matter).

Is that a bug in jQuery or do I have to use it in another way? (I really want to use jQuery because of the event namespacing).

My javascript:

document.getElementById("canvas1").addEventListener("mousemove", function(event){
    self = this;
    draw(event, self);
});

$("#canvas2").on("mousemove", function(event){
    self = this;
    draw(event, self);
});

function draw(ev, canvas){
    var x, y;
     if (ev.layerX || ev.layerX == 0) {
        x = ev.layerX;
        y = ev.layerY;
    } else if (ev.offsetX || ev.offsetX == 0) { 
        x = ev.offsetX;
        y = ev.offsetY;
    }

    var context = canvas.getContext('2d');

    console.log(ev, x, y);
    if (x === undefined || y === undefined) return;
    context.fillStyle = "rgb(0,255,255)";
    context.lineTo(x, y);
    context.stroke();
}
0

1 Answer 1

2

Problem

In jQuery, events don't have layerX and layerY properties because $.event.props.layerX and $.event.props.layerY were removed (and before only worked on browsers that support event.layerX and event.layerY).

And they only have offsetX and offsetY properties on browsers that supports them. There was a ticket to make them available for Firefox too, but was closed as wontfix because of performance reasons.

Solutions

  • Read layerX and layerY from event.originalEvent
  • Calculate offsets manually with jQuery:

    if(typeof event.offsetX === "undefined" || typeof event.offsetY === "undefined") {
       var targetOffset = $(event.target).offset();
       event.offsetX = event.pageX - targetOffset.left;
       event.offsetY = event.pageY - targetOffset.top;
    }
    
  • Calculate offsets manually with JavaScript. To find the position of the target element, you may use this code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.