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

94
Views
Making rectangle on html canvas click

I want to make rectangle on canvas on event 'click'. I've made event listener but when I click rectangle seems to be way of area where I clicked. Basically I want rectangle to appear around the clicked area. This is my code:

 const cursor_pdf = document.getElementsByClassName('react-pdf__Page__canvas')[0];
 cursor_pdf?.addEventListener('click', (e) => {

    const rect = cursor_pdf.getBoundingClientRect();

    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    const marker = cursor_pdf.getContext("2d");
    marker.beginPath();
    marker.lineWidth = "3";
    marker.strokeStyle = "red";
    marker.rect(x, y, 50, 50);
    marker.stroke();
});

After this when I click with cursor on this blue dot ( not really on screen just to point mouse click) Rectangle appears way off click.

enter image description here

But I want it to be like this:

enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

const cursor_pdf = document.getElementsByClassName('react-pdf__Page__canvas')[0];
 cursor_pdf?.addEventListener('click', (e) => {

    const rect = cursor_pdf.getBoundingClientRect();

    //subtract half of the rectangle width/height so it's centered
    const x = e.clientX - rect.left - 25;
    const y = e.clientY - rect.top - 25;

    const marker = cursor_pdf.getContext("2d");
    marker.beginPath();
    marker.lineWidth = "3";
    marker.strokeStyle = "red";
    marker.rect(x, y, 50, 50);
    marker.stroke();
});
canvas {
  border: 3px solid #000;
}
<canvas class="react-pdf__Page__canvas"></canvas>

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!