[英]Dragging an element in HTML5 Canvas using mouse
我创建了一个小程序,在其中显示一个圆圈,并允许用户在HTML5 Canvas中拖动圆圈。
我能够显示圆,但是仅当我单击圆的右下角时,拖动功能才起作用,如果尝试通过单击圆的其他任何位置来拖动它,则它不起作用。 我无法弄清楚如何解决其中的问题。
这是我完整的代码:
<script>
// handle mousedown events
function myDown(e) {
// tell the browser we're handling this mouse event
e.preventDefault();
e.stopPropagation();
// get the current mouse position
var mx = parseInt(e.clientX - offsetX);
var my = parseInt(e.clientY - offsetY);
// test each circle to see if mouse is inside
dragok = false;
for (var i = 0; i < circles.length; i++) {
var r = circles[i];
if (mx > r.x && mx < r.x + r.radius && my > r.y && my < r.y + r.height) {
// if yes, set that circles isDragging=true
dragok = true;
r.isDragging = true;
}
}
// save the current mouse position
startX = mx;
startY = my;
}
// handle mouseup events
function myUp(e) {
// tell the browser we're handling this mouse event
e.preventDefault();
e.stopPropagation();
// clear all the dragging flags
dragok = false;
for (var i = 0; i < circles.length; i++) {
circles[i].isDragging = false;
}
}
// handle mouse moves
function myMove(e) {
// if we're dragging anything...
if (dragok) {
// tell the browser we're handling this mouse event
e.preventDefault();
e.stopPropagation();
// get the current mouse position
var mx = parseInt(e.clientX - offsetX);
var my = parseInt(e.clientY - offsetY);
// calculate the distance the mouse has moved
// since the last mousemove
var dx = mx - startX;
var dy = my - startY;
// move each circle that isDragging
// by the distance the mouse has moved
// since the last mousemove
for (var i = 0; i < circles.length; i++) {
var r = circles[i];
if (r.isDragging) {
r.x += dx;
r.y += dy;
}
}
// redraw the scene with the new circle positions
draw();
// reset the starting mouse position for the next mousemove
startX = mx;
startY = my;
}
}
</script>
我猜想,问题出在function myDown(e)
,但是我无法弄清楚如何修复坐标,因此,如果我单击圆的任何位置,都可以拖动它。
尝试在函数myDown(e)中将if内部for循环更改为:
if (mx > r.x - r.radius && mx < r.x + r.radius && my > r.y - r.radius && my < r.y + r.radius)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.