Search code examples
javascriptangularjsphysicsjs

How to add text to canvas with PhysicsJS


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?


Solution

  • 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...