Spork provides easy access to handling mouse and touch events. Whenever the mouse interacts with the Spork canvas or when the canvas is touched, the functions below are executed. To handle mouse and touch events, we need only define these functions in our programs. When each of these functions is executed, the variables
mouseX and
mouseY are set to the canvas coordinates of the mouse (or touch). When the mouse button is pressed (or the canvas is touched), the variable
mouseDown is set to
true. When the button is released (or the touch ends) this variable is set to false. Follow the links to see simple examples of each function in action.
- onclick() This function is executed whenever a mouse button is clicked in the canvas or the canvas is tapped.
- onmousemove() This function is executed when the mouse or a touch is moved while above the canvas.
- mouseDown This variable is true when a mouse button is pressed or when the canvas is being touched. Otherwise it is false.
Spork Key Events
Spork provides easy access to handling key events.
Whenever a key is pressed three events are "fired."
- As the key goes down, a "keydown" event happens. This event fires repeatedly as long as the key is down.
- When the key is down, a "keypress" event happens.
- When the key is released, a "keyup" event happens.
When a key is pressed, several variables are set.
- keyDown is set to true and remains true as long as the key is down.
- If a character key is pressedkeyChar is set to that character.
- For any key pressed, keyCode is set to a numeric value representing that key.
- If the ALT key is pressed, altKey is set to true. Otherwise, it is set to false.
- If the CTRL key is pressed, ctrlKey is set to true. Otherwise, it is set to false.
- If the shift key is pressed, shiftKey is set to true. Otherwise, it is set to false.
After these variables are set, the function
onkeydown() is called. To have spork respond to key presses, you should define this function.
Spork also provides
onkeypress() and
onkeyup, but we will have little use for them.
Key Codes
The following spork code will alert the value of keyCode when different keys are pressed.
function onkeydown(){
alert(keyCode);
}
You should run this in the spork editor to see some different values. For your convenience, the variables
leftArrow,
rightArrow,
upArrow, and
downArrow have been defined so that you can easily check to see if an arrow has been pressed.