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.
But I want it to be like this:
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>