我正在寻找最快最轻的方法来在JS Canvas上拖放形状和精灵以进行游戏开发.
我开始使用当前鼠标位置和圆圈的起点进行距离检查.它可以工作,但是当它们重叠时我们遇到了问题,而且我不知道在每个“框架”上测试多个精灵和其他形状时它的效果如何.
我宁愿不使用像jQuery这样的库,因为我要求纯粹的速度和轻松,当然要学习实际的方法!这是我在的地方:
//add the canvas listeners and functions canvas.addEventListener("mousemove",mousemove); canvas.addEventListener("mousedown",mousedown); canvas.addEventListener("mouseup",mouseup); function mousemove(e){ mouseX = e.layerX - canvas.offsetLeft; mouseY = e.layerY - canvas.offsetTop; //for each circle stored in my array of Circle objects,is my mouse within its' //bounds? If so,set the circles' (X,Y) to my mouse's (X,Y) for(i=0;i<circArray.length;i++){ dx = mouseX - circArray[i].x; dy = mouseY - circArray[i].y; dist = Math.sqrt((dx*dx) + (dy*dy)); if(draggable && dist < circArray[i].r){ circArray[i].x = mouseX; circArray[i].y = mouseY; } } } function mousedown(){ draggable = true; } function mouseup(){ draggable = false; }
解决方法
这是我用来拖动单个项目的设置.我不知道你是否想要拖动多个东西,这只是一个小小的修改.
在单词中:在mousedown中搜索保留顺序中的命中对象时,您绘制了对象(因此最上面的项目首先被击中),存储此命中项目,然后mousedrag只是将coords / delta连接到该项目.
//start with only the mousedown event attached canvas.addEventListener("mousedown",mousedown); //and some vars to track the dragged item var dragIdx = -1; var dragOffsetX,dragOffsetY; function mousedown(e){ //...calc coords into mouseX,mouseY for(i=circArray.length; i>=0; i--){ //loop in reverse draw order dx = mouseX - circArray[i].x; dy = mouseY - circArray[i].y; if (Math.sqrt((dx*dx) + (dy*dy)) < circArray[i].r) { //we've hit an item dragIdx = i; //store the item being dragged dragOffsetX = dx; //store offsets so item doesn't 'jump' dragOffsetY = dy; canvas.addEventListener("mousemove",mousemove); //start dragging canvas.addEventListener("mouseup",mouseup); return; } } } function mousemove(e) { //...calc coords circArray[dragIdx].x = mouseX + dragOffsetX; //drag your item circArray[dragIdx].y = mouseY + dragOffsetY; //...repaint(); } function mouseup(e) { dragIdx = -1; //reset for next mousedown canvas.removeListener(.... //remove the move/up events when done }
我的js目前还生锈,但这应该给出了这个想法. dragOffsetX / Y用于防止项目在单击时跳转到光标.您也可以只存储旧鼠标坐标并为项目添加增量.
此外,您可以存储对拖动项的引用,也可以存储拖动多个项的引用数组,而不是将索引存储到拖动项.而不是直接操作您的项目,您可以在它们上面放置一个mousedown / drag / up界面让它们处理它.这样可以更轻松地混合其他类型的物品.