首页 > 解决方案 > ES5 Canvas mousedown dragging issue

问题描述

I'm trying to use mousedown to detect when you've held onto an item. For context, I have 2 sprites in an array, and I can detect the click in their bounding box, and it is passing correctly into the mousedownHandler.

spArray[1] is the canvas sprite I'm trying to drag around. clickedBoundingBox is working correctly.

function canvasMouseDownHandler(ev,ctx,spArray){

   if (spArray[1].clickedBoundingBox(ev)){
       console.log("Mousedown successful");

       var mx = ev.offsetX; 
       var my = ev.offsetY;

       spArray[1].x = Math.round(mx-spArray[1].width/2);
       spArray[1].y = Math.round(my-spArray[1].height/2);

}

Currently what happens is it snaps instantly to the mouse position, and it isn't maintaining the dragging. Via console log, I expected to see repeated logging of "mousedown successful"

I was thinking about using a setInterval function to snap the sprite to the mouse position, but then I run into the problem of clearing the interval on mouseup. I'm fairly new to events and I'm struggling to understand this.

Any help is greatly appreciated.

标签: canvasdrag-and-dropdragecmascript-5mousedown

解决方案


If I understood correctly you are expecting MouseDownHandler to be triggered while the mouse moves, I don't know of any language that behaves that way...

  • MouseDown should be a one time event every time the mouse button is pressed
  • just like MouseUp happens one time when the mouse button is released.
  • There should be a MouseMove that is triggered a lot more often.

With that info you can get dragging to work.
Dragging is every move that happens between a MouseDown and a MouseUp


推荐阅读