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

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

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