Seb Lee-Delisle


HTML5 Canvas 3D particles

Yesterday I met Renaun Erickson from Adobe, who told me that he took my basic 3D engine, compiled it with the Flash CS5 beta into an iPhone app, and demoed it the very next day at the 360 Flex conference at Adobe!

HTML5 Canvas 3D particles

It gave me a few ideas about how to optimise it so perhaps I’ll try that soon. But first, I wanted to see whether I could port it to javascript and HTML5 canvas. It turns out that I could, but this time it’s more like 11 lines.*

var scale = fov/(fov+z3d); 
var x2d = (x3d * scale) + HALF_WIDTH;	
var y2d = (y3d * scale)  + HALF_HEIGHT;

By now you’ll recognise this code to convert the 3D x y and z position into 2D x and y, the difference here is that I’m offsetting the coordinate system so that it’s in the middle, which puts the vanishing point in the centre of the screen. (In the Flash version, I just moved the whole container for the particles into the middle.)

function compareZPos(a, b)
	return (b.pos.z-a.pos.z)

This is the bit that sorts the array relative to the z position of each particle, so that when we then go through and draw them all, it starts from the back to the front.

And here’s the bit that draws the image onto the canvas :

	c.drawImage(img,x2d-scale, y2d-scale, scale*2, scale*2);

I’m thinking about making all of this stuff into a slightly better explained tutorial, is this something you’d be interested in? In the meantime, check it out and let me know what you think. In particular I’d like to hear from any javascript experts with any optimisation tips.

HTML5 Canvas 3D Particles

* I know it’s not 11 lines, OK? And perhaps it’d be more apt to call it a 3D lawnmower engine :-)

This entry was posted in HTML5 Canvas and tagged , , . Bookmark the permalink.

21 Responses to HTML5 Canvas 3D particles