HTML5画布点击并拖动绘制方框

问题描述 投票:0回答:1

我正在使用一些代码来查找相对于特定元素(在本例中为 HTML5 画布)的鼠标位置,以绘制红色框。此代码在鼠标按下时给出了正确的起始位置,但在鼠标松开时给出了错误的位置。

如何让它在鼠标松开时工作?

var rect1x, rect1y;
var a, b;

function mouseDown() {
  a = document.getElementById("myCanvas").getBoundingClientRect().left;
  b = document.getElementById("myCanvas").getBoundingClientRect().top;
  rect1x = window.event.clientX - a;
  rect1y = window.event.clientY - b;
}

function mouseUp() {
  var rect2x = window.event.clientX - a;
  var rect2y = window.event.clientY - b;

  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(rect1x, rect1y, rect2x, rect2y);
}
<center>
  <font size=6>Drag to draw a red box</font>
</center>
<div>
  <canvas onmousedown="mouseDown()" onmouseup="mouseUp()" id="myCanvas" width="1600" height="800" style="border:1px solid #000000;">
</canvas>
</div>

javascript html html5-canvas
1个回答
3
投票

ctx.fillRect
需要
x, y, width, height
,而不是
x1, y1, x2, y2

因此将最后一行更改为:

ctx.fillRect(rect1x, rect1y, rect2x - rect1x, rect2y - rect1y);
© www.soinside.com 2019 - 2024. All rights reserved.