简体   繁体   中英

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.

在此处输入图像描述

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM