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

138
Vistas
trying to center html canvas that requires mouse input

I am making this game from this online tutorial. I have centered the game but adding a style tag that adjusts the canvas:

#canvas {
    position:absolute; 
    top:0;bottom:0;right:0;left:0; 
    margin:auto; 
}

It properly centers the puzzle game, however it has now off-centered my mouse position, making it click the tile of the puzzle that is a couple of pixels off, I tried to just get the offset and subtracting it wherever the mouse is, but it doesn't seem accurate, not working well.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Mouse event properties layerX and layerY are non standard. Read-only mouse event properties offsetX and offsetY already contain the (x,y) position of the mouse over the canvas if the mouse is over the canvas.

Hence as a start, try inserting a function to record the mouse position such as

function setMousePos(e) {
  if( e.target.tagName == "CANVAS") {
    _mouse.x = e.offsetX;
    _mouse.y = e.offsetY;
  }
}

and replace inlined code

if(e.layerX || e.layerX == 0){
    _mouse.x = e.layerX - _canvas.offsetLeft;
    _mouse.y = e.layerY - _canvas.offsetTop;
}
else if(e.offsetX || e.offsetX == 0){
    _mouse.x = e.offsetX - _canvas.offsetLeft;
    _mouse.y = e.offsetY - _canvas.offsetTop;
}

wherever it occurs with setMousePos(e).

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