Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
Why getBoundingClientRect returns null when pointing to a negative coordinate position in svg?

The trick part might be the viewBox="-50 0 150 100". But I really need to get the negative coordinates.

Please take a look at the demo below:

$('svg').click(function(e){
  const { farthestViewportElement: svgRoot } = e.target;
  const dim = svgRoot.getBoundingClientRect();
  const x = e.clientX - dim.left;
  const y = e.clientY - dim.top;
  $('#cord-track').val(`x: ${x}, y: ${y}`);
})
svg {border:1px dashed blue}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>When you click mouse in the red rect, it works perfectly</p>
<p>When you click mouse in the left blank zone, it throws an error, so that I can't trace my x and y values. How do I fix it?</p>
<svg width="100px" id="test" viewBox="-50 0 150 100">
<rect x="0" y="0" width="100" height="100" fill="red">
</svg>
<input id="cord-track" />

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

https://www.google.com/search?q=FarthestViewportElement

The documentation for FarthestViewportElement says:

The farthest ancestor ‘svg’ element.
Null if the current element is the outermost svg element

Thus when you click the <svg> itself, you get a null value

So instead, get that <svg> with e.target.closest("svg")

Note: this will ofcourse fail when you have <svg> inside <svg>;
use a full size <rect> as first element then for a catch all

MYSVG.onclick = e => {
  let svg = e.target.closest("svg");
  let path = e.composedPath().map(el => el.nodeName ).join(",");
  console.log("CLICKED:",e.target.nodeName,"IN:",svg.id,"CLICK PATH:",path);
}
svg {
  width:180px;
  border: 1px dashed blue
}
<svg id="MYSVG" viewBox="-50 0 150 100">
    <rect x="0" y="0" width="100" height="100" fill="red"/>
</svg>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda