[英]Making rectangle on html canvas click
I want to make rectangle on canvas on event 'click'.我想在事件“点击”时在 canvas 上制作矩形。 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.在此之后,当我在这个蓝点上点击 cursor 时(不是真的在屏幕上只是为了点鼠标点击)矩形出现在点击的地方。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.