4

我使用相同的代码来查找相对于特定元素(在本例中为 HTML5 画布)的鼠标位置。这适用于鼠标按下,但会在鼠标抬起时中断。我怎样才能让它在鼠标上工作?

<!DOCTYPE html>
<html>
<body>

<h1>This is page one; here we will play with HTML5</h1>

<a href= "../index.html">This link takes you back to home</a>

<div> <canvas onmousedown="mouseDown()" onmouseup="mouseUp()" 
id="myCanvas" width="1600" height="800" style="border:1px solid #000000;">
</canvas> </div>

<script type="text/javascript">

var rect1x = rec1y;
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);
}

</script>

<center><font size=1>Draw!</font></center>

</body>
</html>
4

1 回答 1

3

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

所以将最后一行更改为:

ctx.fillRect(rect1x, rect1y, rect2x - rect1x, rect2y - rect1y);
于 2012-10-08T15:25:22.730 回答