首页 > 解决方案 > 如何使用 Matter.js 和 p5.js 将文本放在矩形中

问题描述

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

这就是我的 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();
    }
  }

标签: javascripttextp5.jsmatter.js

解决方案


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

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()如果您想在某些时候使文本居中,您可能也会感兴趣。

这是一个工作示例


推荐阅读