I have created a small program where I display a circle and allow the user to drag the circle within HTML5 Canvas.
I was able to display the circle but the drag functionality is working only if I click on below right corner of my circle, if I try to drag it by clicking on anywhere else of circle then it is not working. I am not able to figure out how to fix the issue in it.
Here is my complete code:
<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>
I guess, the issue is with function myDown(e)
, but I was not able to figure out how to fix the co-ordinates so that if I click on anywhere of the circle it should be draggable.
尝试在函数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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.