I am building an small CAD app that allows the user to select items and then press LEFT/RIGHT arrow keys to move them.
The problem
The problem is that the function that moves the elements takes too long to process if my canvas has many elements drawn on it.
The worst is that if the user presses and holds the arrow keys, the function needs to get fired so many times that I get the dreaded Unresponsive Script alert from my browser.
Even if the user burst-fires a keypress instead of holding it, I still have a problem.
So I figured that the way to go, is:
- Collect keypresses and after e.g 2000ms to fire up the function with the appropriate keypressCounter - the number of keypresses collected before keyUp
The problem with the method above:
The user will have to wait for the timeout even if just one keypress was made - which does not have a huge overhead - therefore the ''crude'' method described above is less than ideal. It will make the nudge functionality feel cludgy where it could be fast.
What would be the most correct way to go around this? Any suggestions are welcome since the solution I suggest above seems rather crude
Notes:
I would appreciate code snippets, even rudimentary ones. I'm still in my early coding stages. Or at least a comprehensive explanation to any proposed solutions.
I am using Paper.js as the canvas library to draw the items, but that shouldn't be a factor in any solution
The code this far:
//Keybinding ''right'' arrow key - Fires up the function to nudge left.
$(document).keydown(function (e) {
if (e.which === 39) {
nudgeSelection("right");
}
});
//Function that moves the selected element(s). Accepts direction as parameter.
function nudgeSelection(direction) {
var selected = paper.project.selectedItems;
for (var i = 0; i < selected.length; i++) {
switch (direction) {
case "up":
selected[i].position.y = selected[i].position.y - 1;
break;
case "down":
selected[i].position.y = selected[i].position.y + 1;
break;
case "left":
selected[i].position.x = selected[i].position.x - 1;
break;
case "right":
selected[i].position.x = selected[i].position.x + 1;
break;
}
}
}