Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!