I'm looking for the fastest and lightest way to drag and drop shapes and sprites on a JS Canvas for game-development purposes.
I've started by doing distance checks using the current mouse position and the origins of circles. It works, but when they overlap we have problems and I don't know how well this will work when testing for multiple sprites and other shapes yet on each 'frame'.
Any comments or pointers to better methods are appreciated!
I'd rather not use a library like jQuery since I'm going for pure speed and lightness and of course to learn the actual methods! Here's where I'm at:
//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;
}