如何使用 Matter.js 和 p5.js 将文本放在矩形中

How to put text in rectangle using Matter.js and p5.js

我按照本教程学习了如何使用 matter.js 的 codetrain。 我想知道如何将文本放在矩形中? 现在,文本是什么并不重要,只要我能以某种方式将文本放入其中即可。

这就是我的 javascript 现在的样子 我正在使用 matter.js 库和 p5.js

var Engine = Matter.Engine,
  World = Matter.World,
  Bodies = Matter.Bodies;

var engine;
var world;
var boxes = [];

var ground;


function setup() {
    createCanvas(window.innerWidth, window.innerHeight);
    engine = Engine.create();
    world = engine.world;
    Engine.run(engine);
    var options = {
      isStatic: true
    }
    ground = Bodies.rectangle(200, height, width, 10, options);
    World.add(world, ground);
  }


function Box(x, y, w, h) {
    this.body = Bodies.rectangle(x, y, w, h);
    this.w = w;
    this.h = h;
    World.add(world, this.body);

    this.show = function(){
      var pos = this.body.position;
      var angle = this.body.angle;

      push();
      translate(pos.x, pos.y);
      rotate(angle);
      rectMode(CENTER);
      strokeWeight(1);
      stroke(255);
      fill(0);
      rect(0, 0, this.w, this.h);
      pop();
    }
  }

function mousePressed(){
  boxes.push(new Box(mouseX, mouseY, 100, 100))
}

  function draw() {
    background(0);
    for (var i = 0; i < boxes.length; i++) {
      boxes[i].show();
    }
  }

您可以为此使用 p5js text() 函数:

this.show = function () {
    var pos = this.body.position;
    var angle = this.body.angle;

    push();
    translate(pos.x, pos.y);
    rotate(angle);
    rectMode(CENTER);
    strokeWeight(1);
    stroke(255);
    fill(0);
    rect(0, 0, this.w, this.h);
    stroke(255);
    // translate(-this.w/2, -this.h/2); // Is you want to move the text at the top left corner
    fill(255);
    stroke(255);
    text("foo", 0, 0);
    pop();
};

text() 将要绘制的字符串及其位置作为参数。因为你已经 translate(pos.x, pos.y); 你可以简单地使用 0,0 作为坐标。如果您想在某个时候将文本居中,您可能也对 textWidth() 感兴趣。

Here is a working example