Introducing Box2dWeb: create Box2D projects in HTML5 – using your own graphic assets

When I first introduced Box2dWeb to create Box2D projects in HTML5, some readers wondered how to use your own graphic assets rather than the basic debug draw.

So here it is the whole process, which isn’t that much different than doing the same with AS3.

First, I am including the image of a crate in my HTML page, inside an hidden div, look at lines 9-11:

Then, once I have the images, we just need to define the getContext("2d") object, which is a built-in HTML5 object, with many properties and methods for drawing paths, boxes, circles, text, images, and more, at line 13 in our js:

The remaining code is almost the same you are used to see in every Box2D project when you update the world, basically the core of the whole example can be found in these five lines:

The main difference between this way of displaying assets and its AS3 counterpart is in AS3 we place the (eventually) rotated assets directly on the stage, while in HTML5 we have to save and rotate the whole context, rotate it, then place the unrotated image and finally restore the context.

And this is the result:

Click on the canvas to create a skinned crate.

  • sh4dows

    I’am waiting for more nape physics tutorials:) v2.0 was released it’s looks very nice.
    cheers.

  • MC

    nice…

  • The demo is interesting, but I got a problem with Internet Explorer 9. The texture is offset. I can see the top-left corner of the texture aligned with the center of the box silhouette. I tried with Chrome and Firefox and it worked perfectly. I guess the web version of Box2D has issues with the browsers’ differences. I do not know if there is simple fix, but I still prefer the integration with Flash.

  • Kamaji

    Thanks for your tutorial, is really useful for me.

  • It’s nice, I’m going to try something similar with a crossword I mean in spanish crucigrama :)

  • Thanks so much for this tutorial, been looking around for some code on it.

  • Yaary

    this is great. buggy on my ie though. has a colored shadow behind

  • Jon

    This method seems to get all screwy when using a box2d object that’s more of a long rectangle than a perfect square, especially when I try to stretch the image a little bit to make sure the image is the same size as the box.

    Any thoughts on a variant to fix this?

  • Trefor

    Been playing with this but having problems with adding an object with an initial vector applied not just gravity.
    Do you have any pointers?

  • Do not know how to get the js files
    box2dweb.js and main.js

    Are these files open source and where to find?