views:

3153

answers:

3

I want to draw a 3d ball or sphere in html 5.0 canvas. I want to understand the Algorithm about how to draw 3d sphere. Who can share this with me?

Thanks in advance !

A: 
David
given that the light source doesn't change, he can also prerender it and just blit a bitmap ;^)
Toad
+3  A: 

To see some examples of doing 3D in canvas you can look at: http://www.canvasdemos.com/2009/02/26/3d-on-2d-canvas/

You will need to model a sphere, and have it be varying colors so that as it rotates you can see that it is not only a sphere, but being rendered.

Otherwise, a sphere in space, with not point of reference around it looks like a circle, if it is all one solid color.

To start with you will want to try drawing a circle with rectangles, as that is the main primitive you have.

Once you understand how to do that, or create a new primitive, such as a triangle, using the Path method, and create a circle, then you are ready to move it to 3D.

3D is just a trick, as you will take your model, probably generated by an equation, and then flatten it, as you determine which parts will be seen, and then display it.

But, you will want to change the color of the triangles based on how far they are from a source of light, as well as based on the angle of that part to the light source.

This is where you can start to do optimizations, as, if you do this pixel by pixel then you are raytracing. If you have larger blocks, and a point source of light, and the object is rotating but not moving around then you can recalculate how the color changes for each triangle, then it is just a matter of changing colors to simulate rotating.

The algorithm will depend on what simplifications you want to make, so as you gain experience come back and ask, showing what you have done so far.

James Black
Those examples are amazing. Although they suggest viewing them in Chrome, the waving flag picture and the iPhone (default renderer) worked pretty well in Safari.
Peter M
I think Chrome is just because it may be faster, but now Safari 4, Firefox 3.5, Chrome and Opera 10 should all be able to show these well.
James Black
+1  A: 
Sam Hasler
The JavaScript+Canvas demo only works in Firefox. Chrome gives me the same error as this question: http://stackoverflow.com/questions/982000/firefox-throwing-a-exception-with-html-canvas-putimagedata
Sam Hasler
Haven't had time to look at the fast version but there are some simple improvements that get it up to 40fps.
Sam Hasler