canvas - 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.
解决方案
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
推荐阅读
- php - 在 Laravel Blade 中访问多维数组值
- c++ - 为什么 Clang 为引用和非空指针参数生成不同的代码?
- objective-c - 在 AppKit 中初始化选定的单选按钮 (NSButton) 组
- python - Pytesseract 图像到字符串问题
- python - 无法导入 main.py 中所需的 python 文件
- mongodb - 如何在快速路由器中使用 Mongoose 查找查询?
- python - 我如何使用 discord py 在特定频道中固定具有特定角色的用户的图像
- python - OSError:标签:找不到文件“Gilroy-light.ttf”
- python - MongoDb、Dash 和 Python
- android - 为 Android 开发电视遥控器应用程序的步骤是什么?