Preventing Default Keyboard Behavior
When relying on the keyboard, the thing you need to keep in mind is that everything from your browser to your operating system is listening to the keyboard as well. Strange and unexpected things happen when your keyboard is used. In our case, the arrow keys are used to scroll your page up and down (and occasionally left and right). Even if users have their focus on the canvas
, tapping the arrow keys will cause your entire page to scroll if your content gets large enough to display scrollbars. You don’t want that.
The way you fix this is very simple. In your moveSomething
function (aka the event handler), simply add a call to preventDefault
as shown in line 16:
function moveSomething(e) {switch(e.keyCode) {case 37:deltaX -= 2;break;case 38:deltaY -= 2;break;case 39:deltaX += 2;break;case 40:deltaY += 2;break;}e.preventDefault();drawTriangle();}
The preventDefault
method prevents your browser from reacting to any keyboard events as long as your page has focus. This ensures that you can do all sorts of keyboard-ey things inside your canvas
without worrying about your key presses accidentally triggering normal (yet unwanted) browser behavior.