Using HTML 5 to recreate an illusion

One of the people I follow on twitter linked to this visual trick. It’s a classic illusion that I’ve seen plenty of times before, but the first thing that went through my mind was, “Hey! I can probably create that in HTML 5!” To make sure I hadn’t been trumped in that, I checked out the page’s source and saw that it simply used used a repeating background image.

So I said “Great! This will give me a quick lesson in the HTML 5 canvas tag!”

I haven’t done much playing with HTML 5 as of yet. Mostly I’ve been trying to learn all the new tricks of CSS3. So this was all new to me. But the canvas tag is pretty simple. The HTML itself is actually almost non-existent:

<body onLoad=draw_sc() onResize=draw_sc()>
<canvas id="scintillation"></canvas>
</body>

draw_sc() is the javascript function where all the magic happens. Using canvas, you have to getElementByID and then define the canvas context using getContext("2d"). Apparently there are some browsers working on 3D contexts, but for the time being, 2D is what you’ve got. The canvas tag only has width and height properties, so I set those to the window size and added an onResize call to body, just to make things easier so you don’t have to refresh the page.

Once you have the context defined, it’s just a simple set of loops which use the fillRect function which takes the upper left and lower right corner coordinates and the fillStyle attribute to define the color of the rectangle to define the black squares and the grey cross hatches. I could have just painted the background grey, but since I was practicing new stuff, I figured I’d go with the slightly more complicated process for the experience. The white circles are where it gets kind of interesting.

There is no circle method, so instead you use arc. An arc is just a section of a circle, so if you just make it cover the full circumference, then you have a circle. arc requires coordinates for the center of the circle, the radius, the starting and end positions of the arc in radians (for a full circle, that’s 0 and 2*pi, respectively), and the direction of the line (false = counter-clockwise, true = clockwise).

But that just defines the “path” that will be drawn. After that, you have to give the path a color using the strokeStyle attribute, and then telling the canvas to stroke() the path. And then, you define the fillStyle and tell it to fill(). Tuck all of that into nested loops to work your way across the grid and you’re good to go.

Here’s the final result. You can check out the source for the full script.

Leave a Reply

Close Bitnami banner
Bitnami