Mouse & Keyboard
Make interactive programs! Follow the mouse, respond to clicks, and use keyboard controls.
The built-in variables mouseX and mouseY always hold the current mouse position on the canvas. Use them to make shapes follow your cursor!
Try it!Try adding a second circle that follows the mouse but is offset by 50 pixels!
Here's a trick: if you DON'T clear the background each frame, everything you draw stays on screen. Combine that with mouseIsPressed to make a simple drawing program!
Use keyIsDown() to check if a key is currently held down. This is perfect for game controls because it works smoothly — no delays, and you can check multiple keys at once.
The keyPressed() function fires once each time a key goes down — unlike keyIsDown() which checks continuously. This is useful for things that should happen just once per press, like jumping or toggling something.
Let's combine mouse and keyboard input into one interactive sketch. You can click to place shapes and use the keyboard to change what gets placed!
What to try next
- Add an eraser mode that draws with the background color when you press E
- Make a character that can move with WASD and shoot a projectile when you press Space
- Create a color picker — use mouseX to control hue, mouseY to control brightness
- Build a simple Etch A Sketch using arrow keys to move a drawing cursor