Quiero hacer un rectángulo en el lienzo en el evento 'clic'. Hice un detector de eventos, pero cuando hago clic en el rectángulo, parece ser una forma de área donde hice clic. Básicamente, quiero que aparezca un rectángulo alrededor del área en la que se hizo clic. Este es mi código:
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(); });Después de esto, cuando hago clic con el cursor en este punto azul (no realmente en la pantalla, solo para apuntar con el clic del mouse), el rectángulo aparece muy lejos del clic.
Pero quiero que sea así:
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>