I’ve been working on a graphical web project that requires an interactive roll of a pair of dice. Dice are cubes and would be most con

Charles Petzold: Rudimentary 3D on the 2D HTML Canvas

submited by
Style Pass
2024-10-27 06:00:03

I’ve been working on a graphical web project that requires an interactive roll of a pair of dice. Dice are cubes and would be most convincingly rendered with 3D graphics. But because these dice are only a tiny part of this project, I was reluctant to call out the big guns. I didn’t want to wrestle with the low-level WebGL to do 3D graphics or even a friendlier WebGL wrapper such as three.js.

Moreover, most of the project involving the dice uses conventional HTML5 Canvas graphics, and you can’t mix those 2D graphics and WebGL on the same canvas element. (WebGL supports 2D graphics as well as 3D but it’s a whole different animal.) For these reasons, I felt I could simulate 3D dice with much simpler 2D graphics and a little math.

You can use the three sliders to rotate the cube around three orthogonal axes: the horizontal X axis, the vertical Y axis, and the Z axis that conceptually extends out of the screen. Because these rotations are compounded, the effects are mathematically rather complex and might be puzzling.

Leave a Comment