Я создал небольшую программу, в которой я показываю круг и позволяю пользователю перетаскивать круг в холсте HTML5.Перетаскивание элемента в HTML5 Холст с помощью мыши
Мне удалось отобразить круг, но функция перетаскивания работает только в том случае, если я нажму на правый угол моего круга, если я попытаюсь перетащить его, щелкнув в любом месте круга, тогда он не работает. Я не могу понять, как исправить эту проблему.
Вот мой полный код:
<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)
, но я не смог понять, как исправить координаты, так что если я нажимаю на любой точки круг он должен быть перетаскиваемым.
Вы, кажется, проверяя поле вокруг положения курсора мыши? Просто проверьте, меньше ли разница между мышью и центром круга, чем радиус круга. –