0

I'm doing a simple project with Physics.JS and I want to be able to add text to a PhysicsJS World. I looked in the documentation but I couldn't find something that can allow me to do such thing. Is there a way to add text and to also be able to manipulate parts of it, like increasing velocity, restitution and other things from the engine?

Darko
  • 39
  • 1
  • 6
  • If you want to render text that interacts with the physics of the world, you'll need to create a physics body in the shape of the text you want. As for statically drawing text, PhysicsJS isn't really built for that. – Mike Cluck Dec 23 '16 at 17:12
  • Do you mean draw out each character of the text using convex-polygon as a way to create a body? – Darko Dec 23 '16 at 17:25
  • Yup. That is if you want it to act as a physical body. – Mike Cluck Dec 23 '16 at 17:28
  • Not really.. I just want the text to slide from left to right, and if there's an image, I want the image to act as a body, which I know how I would make... do you have any ideas how I can make text without generating vertices for each character? Is it good practice to alter the canvas element that PhysicsJS is using for something like this? – Darko Dec 23 '16 at 19:46

1 Answers1

1

Just extend a rectangle body, and change its view to a canvas with text on it:

 Physics.body('text', 'rectangle', function (parent) {
      var canv = document.createElement('canvas');
      canv.width = 310;
      canv.height = 60;
      var ctx  = canv.getContext("2d");
      ctx.fillStyle = "#ffffff";
      ctx.textAlign = "left"
      ctx.textBaseline = "top";
      ctx.font = "80px sans-serif";

      return {
           // Called when the body is initialized
           init: function(options) {
               parent.init.call(this, options);
               ctx.fillText(options.text,0,0);
            },
            // Called when the body is added to a world
            connect: function() {
                this.view = canv;
            }
      }
  });

Then, to instantiate it:

 Physics.body('text', {
     x: 400,
     y: 570,
     width: 310,
     height: 60,
     text: "Some text here",
 })

You specify the string of text via options.text.
Of-course, one would make it more dynamic, by allowing to specify the font parameters in the options, then auto-calculate the dimension on init, and so on...

Yuval A.
  • 5,849
  • 11
  • 51
  • 63