[英]Making rectangle on html canvas click
我想在事件“点击”时在 canvas 上制作矩形。 我已经制作了事件侦听器,但是当我单击矩形时似乎是我单击的区域。 基本上我希望矩形出现在点击区域周围。 这是我的代码:
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();
});
在此之后,当我在这个蓝点上点击 cursor 时(不是真的在屏幕上只是为了点鼠标点击)矩形出现在点击的地方。
但我希望它是这样的:
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.