Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect value of click event layerX on svg foreignObject element

On svg viewport zoomed in state (bigger svg width than viewport width). The foreignObject click event layerX property is incorrect on Safari and Chrome. In the following example click on center of yellow rect and see the console output.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body style="margin:0">
  <svg viewBox="0 0 200 200" style="height: 400px; width: 400px;" xmlns="http://www.w3.org/2000/svg">
    <rect width="100%" height="100%" fill="red"/>
    <foreignObject x="50" y="50" width="100" height="100">
      <div style="background-color: yellow; width: 100px; height:100px;">
      </div>
    </foreignObject>
  </svg>
</body>
</html>

Try it on chrome, safari and firefox. Notice you will get different result on each browser. The chrome and safari results are meaningless and firefox calculates without considering viewport state. Is there any workaround to this issue?

like image 885
Ara Yeressian Avatar asked Jun 29 '19 21:06

Ara Yeressian


1 Answers

The trick is to not use layerX , instead use

event.clientX - rect1.getBoundingClientRect().left

I updated the example to work correctly. Now I get consistent result among chrome, firefox and safari.

like image 177
Ara Yeressian Avatar answered Sep 25 '22 02:09

Ara Yeressian