简体   繁体   中英

(Firefox) Javascript mousemove not the same as jQuery mousemove

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();
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM