簡體   English   中英

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

[英]How to add text to canvas with PhysicsJS

我正在使用Physics.JS做一個簡單的項目,並且希望能夠向PhysicsJS World添加文本。 我查看了文檔,但找不到能使我執行此操作的東西。 有沒有一種方法可以添加文本,也可以操縱文本的某些部分,例如提高速度,恢復原狀以及引擎提供的其他功能?

只需擴展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;
            }
      }
  });

然后,實例化它:

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

您可以通過options.text指定文本字符串。
當然,通過允許在選項中指定字體參數,然后在init上自動計算尺寸,等等,可以使它更加動態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM