Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-browser solution for replacing the use of event.layerX and event.layerY

I'm trying to adapt some code from a simple app that uses Raphael to allow users to draw circles and rectangles on a canvas. (original code at https://gist.github.com/673186)

The original code used an older version of jQuery and worked fine. See http://jsfiddle.net/GHZSd/

Using an updated version of jQuery, however, breaks the example. See http://jsfiddle.net/GHZSd/1/

The reason for this is that event.layerX and event.layerY are no longer defined in the new version of jQuery. My question is - what code I can use to replace those values? I've tried a couple things just by doing some math (event.originalEvent.layerX/layerX still exist for now so I'm just trying to add/subtract some stuff that will result in those values) but so far what works on one browser doesn't work on all of them.

Sorry if this has been asked before but I wasn't able to find a concrete answer on Stack Overflow or anywhere else.

like image 473
zeke Avatar asked Apr 12 '12 22:04

zeke


2 Answers

So, i thought a little about this problem, since the Chrome team wants to remove layerX and layerY for strange reasons.

First, we need the position of your container :

var position = $paper.offset();

(for those reading without the fiddle opened, $paper is the div where the svg will be drawn)

It gives us two coords, position.top and position.left, so we know where in the page is the container.

Then, on click, we use e.pageX and e.pageY, which are the coords of the page. To emulate layerX and layerY, we use (e.pageX - position.left) and (e.pageY - position.top)

Et voilà : http://jsfiddle.net/GHZSd/30/

Works on chrome, Safari, FF and Opera.

like image 178
mddw Avatar answered Sep 21 '22 03:09

mddw


const bbox = e.target.getBoundingClientRect();
const x = e.clientX - bbox.left;
const y = e.clientY - bbox.top;
like image 29
Sergey Avatar answered Sep 20 '22 03:09

Sergey