简体   繁体   English

如何使用PhysicsJS向画布添加文本

[英]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. 我正在使用Physics.JS做一个简单的项目,并且希望能够向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? 有没有一种方法可以添加文本,也可以操纵文本的某些部分,例如提高速度,恢复原状以及引擎提供的其他功能?

Just extend a rectangle body, and change its view to a canvas with text on it: 只需扩展rectangle主体,然后将其view更改为带有文本的画布即可:

 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 . 您可以通过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... 当然,通过允许在选项中指定字体参数,然后在init上自动计算尺寸,等等,可以使它更加动态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM