Thursday, February 19th, 2009

Box2D Ported to JavaScript Using Canvas

Category: Canvas, Examples

Robert Kieffer recently told us about Box2DJS, an automated port of the popular Box2D physics library to JavaScript using <canvas> for the rendering.

Using Box2DJS, you can create a flatland-esque 2D world that obeys Newtonian physics:

  1. var worldAABB = new b2AABB();
  2. worldAABB.minVertex.Set(-1000, -1000);
  3. worldAABB.maxVertex.Set(1000, 1000);
  4. var gravity = new b2Vec2(0, 300);
  5. var doSleep = true;
  6. var world = new b2World(worldAABB, gravity, doSleep);

and then you can add in your own objects and make them do interesting things. Here’s a simple example of adding a circular into the world created above:

  1. var circleSd = new b2CircleDef();
  2. circleSd.density = 1.0;
  3. circleSd.radius = 20;
  4. circleSd.restitution = 1.0;
  5. circleSd.friction = 0;
  6. var circleBd = new b2BodyDef();
  7. circleBd.AddShape(circleSd);
  8. circleBd.position.Set(x,y);
  9. var circleBody = world.CreateBody(circleBd);

There’s a bunch of examples of Robert’s site, and of course you can refer back to Box2D for more. Interesting use of canvas!

Posted by Ben Galbraith at 7:00 am

4.6 rating from 34 votes


Comments feed TrackBack URI

This is so cool. I can play all day with this one. :)

Comment by Spocke — February 19, 2009

Very smart! More Kudos++

Comment by oopstudios — February 19, 2009

Where’s Robert’s site? I’m iterested in his bunch of examples.

Comment by technohippy — February 19, 2009

Robert Kieffer here. I think there’s been a bit of a misunderstanding. I don’t have any affiliation with this project. I just brought it to the attention of our hosts here at Ajaxian. I’ve asked them to correct it.

The only demos I’ve found are the ones that you access by right clicking in the canvas element on the main Box2DJS page.

Comment by broofa — February 19, 2009

hasn’t this been around for like 2 years in javascript form? old news..

Comment by leptons — February 19, 2009

The developer here;-) I see. Thanks Robert.

Comment by technohippy — February 19, 2009

Leave a comment

You must be logged in to post a comment.