Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda