如何使用 PhysicsJS 添加文本到 canvas

How to add text to canvas with PhysicsJS

我正在使用 Physics.JS 做一个简单的项目,我希望能够向 PhysicsJS 世界添加文本。我查看了文档,但找不到可以让我做这样的事情的东西。有没有一种方法可以添加文本并能够操纵其中的一部分,例如提高速度、恢复原状以及来自引擎的其他东西?

只需扩展一个 rectangle 正文,并将其 view 更改为带有文本的 canvas:

 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;
            }
      }
  });

然后,实例化它:

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

您通过 options.text 指定了文本字符串。
当然,通过允许在选项中指定字体参数,然后在初始化时自动计算尺寸等等,可以使其更加动态...