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

141
Visualizações
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 Respostas
Responde à pergunta

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 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