I’m using some code to find the mouse position relative to a specific element (in this case the HTML5 canvas) to draw red boxes. This code gives the correct starting position on mouse down, but gives the wrong position on mouse up.
How can I make it work on mouse up?
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>
ctx.fillRecttakesx, y, width, height, notx1, y1, x2, y2so change that last line to: