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

174
Visualizações
Get canvas pixel position from mouse coordinates

I have a 16x16 canvas that is scaled with CSS (width:90%; height: auto;) and I'm attempting to convert mouse coordinates on the canvas to one of the 16x16 pixels. I'm taking it from an onmousemove event, and while I can get the raw screen coordinates, I need to get where it lies on the canvas.

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

0

Try this:

const canvas = document.querySelector( 'canvas' );

canvas.addEventListener( 'mousemove', event => {
    
    const bb = canvas.getBoundingClientRect();
    const x = Math.floor( (event.clientX - bb.left) / bb.width * canvas.width );
    const y = Math.floor( (event.clientY - bb.top) / bb.height * canvas.height );
    
    console.log({ x, y });
  
});
html,body { height: 100%; }
canvas { width: 100%; height: 100%; }
<canvas width="16" height="16"></canvas>

So you simply take the coordinate, take of the offset of the canvas (fullscreen that would be 0), then divide it by the visual width of the canvas and multiply by the actual width of the canvas. If you floor that you get a rounded pixel coordinate.

The above code works for any size canvas, since it keeps in mind the offset it has from the screen (also client in mouse coordinate). SO whatever the width of your canvas, this should return the correct pixel.

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