Bouncing Canvas Balls with Gravity and Friction

See the Pen Canvas Bouncing Balls with Gravity and Friction by Brian Cribb (@briancribb) on CodePen.

I went a little crazy with this one. I know it doesn’t look like much, but there’s a lot going on inside that canvas thingy. If you click on the button or on the canvas, a bunch of black circles will bounce around with their own vectors, speeds, elasticity, and with a shared bit of gravity. (Eventually they’ll stop.) If you want to change somethings, just put numbers into the input boxes. If there’s nothing, then default values will be used. If you enter a letter instead of a number, you’ll get an error.

What was I trying to do?

The idea was to play around with some physics and have a go at some form validation, while using all the wonderful fanciness of requestAnimationFrame. I also wanted to use a prototype class instead of just regular objects. It turned out well, but I did catch a bad case of Shiny Object Syndrome before the end.

Javascript classes aren’t quite the same as Flash classes, but they’re pretty close. You can have public variables, private variables, methods… all the good stuff. It’s supposed to keep your code tidy, but I have to admit that I started going crazy with the methods I was building.

How much friction should the floor have? How bouncy should these things be? What kind of gravity should I use? It’s pretty easy to get excited and build bunches of things you won’t actually use. It lost a big chunk of free time just watching things bounce. Sad, really.

Input Fields and Type Coercion

Javascript lets you play fast and loose with variable types, so I wanted to play with that a bit as well. If the user is going to enter values, how do I prevent them from putting letters instead of numbers? Will the input see the “1” as a string or a number? What to do? I wanted to run some tests but I didn’t really need an actual form, so I just tossed some inputs into a styled div tag and targeted them with JavaScript.

For validation, I wound up using the minus-zero trick to kind of force the input into a number. If this checks out, we’re okay. If it blows up and yields NaN (not a number) then we need to toss out an alert and refuse to bounce.

Finally, I decided to make the canvas itself a button. It might help with mobile devices, just in case the submit button winds up below the fold. (You shouldn’t have to hit the button and then scroll up quickly in order to see the action.)