【问题标题】:HTML5 canvas click and dragHTML5 画布单击并拖动
【发布时间】:2012-10-09 00:28:38
【问题描述】:

我正在使用相同的代码来查找相对于特定元素(在本例中为 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>

【问题讨论】:

  • 'Breaks' 不是描述问题的好方法。实际发生了什么?您是否已采取任何措施来调试问题?
  • 休息是什么意思?它会给出错误吗?或者它只是没有给你预期的价值?

标签: javascript html html5-canvas


【解决方案1】:

ctx.fillRect 采用 x, y, width, height,而不是 x1, y1, x2, y2

所以将最后一行更改为:

ctx.fillRect(rect1x, rect1y, rect2x - rect1x, rect2y - rect1y);

【讨论】:

  • 这正是我想说的。 :) 即 ctx.fillRect(xPos, yPos, width, height);
猜你喜欢
  • 1970-01-01
  • 2014-12-02
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 2013-10-05
  • 2014-03-09
相关资源
最近更新 更多