I’ve been teaching a JavaScript class for high school students as part of my side gig at the local Upward Bound program. We covered the basics in four sessions (three last fall and one in January of this year). Our next session will move beyond the basics by applying them to a new context: HTML Canvas. Playing around with Canvas and JavaScript this morning, I ended up writing this little generative art widget which draws rectangles of random size, color, and opacity:
See the Pen Canvas Basics 4: Random Rects by James “Wheatbread” Martin (@jamesnotjim) on CodePen.
I think this will be one of our projects. We’ll work up to it via several simpler steps, like this one, which just draws a series of overlapping, static squares:
See the Pen Canvas Basics 3 by James “Wheatbread” Martin (@jamesnotjim) on CodePen.
The one above offers a little bit of polish in that it uses an object (“colors
“) to store the color codes, which lets you define a fillStyle
or strokeStyle
as colors.gray
or colors.black
, which makes the code easier to understand while also making it easier to reuse colors or to change your mind about the entire color scheme. My first versions hardcoded those RGB values, then I got wise and defined them as constants before getting a bit wiser and defining them in an object. That bit of refactoring will also find its way into the lesson.
This also gives us an excuse to talk about generative art, which I’ve always found quite interesting. The idea of thirty lines of code creating an ever-evolving image is intriguing and a little spooky, to be honest.
Anyway, I’m sharing it here in case anyone else finds it interesting and/or useful.
Credits
The feature image for this post is a cropped version of this image by Mitchell Luo via Unsplash and is used according to the Unsplash License. Thanks to Mitchell for making this image available for free and to Unsplash for hosting it.