javascript - 如何使用 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();
}
}
解决方案
您可以为此使用 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()
如果您想在某些时候使文本居中,您可能也会感兴趣。
推荐阅读
- ionic3 - 在 Windows 应用程序中按退格键触发离子搜索栏错误事件
- google-maps - 如何使用谷歌地图插件添加标记并在标记上设置自定义点击事件?
- r - R Studio 包安装问题
- itk - 不同像素间距和切片厚度的 ITK 过滤器
- android - 如何在android editText中显示两位小数?
- javascript - 删除使用“signature_pad”生成的签名周围的空白/空格
- angular - 使用 APP_INITIALIZER 将自定义数据注入服务
- javascript - 组件未在重定向时呈现
- r - 如何在R中根据因子的水平复制行
- python - 在 spacy (或 textblob 中的 np_extractor )中执行 noun_chunks 时,如何添加一些我已经知道的名词短语?