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

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

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