属性包括 body.render.fillStyle
、body.render.strokeStyle
和 body.render.lineWidth
。
你可以将它们传递给 Body.create(options)
,或者更常见的情况是,如果你在使用工厂,则将其传递给工厂函数。
Bodies.rectangle(0, 0, 100, 100, {
render: {
fillStyle: 'red',
strokeStyle: 'blue',
lineWidth: 3
}
});
您也可以使用精灵,参见代码
如果您需要更多渲染控制,最好克隆Render.js,自定义它并通过Engine.create(element, options)
将其作为engine.render.controller
传递到引擎中。
正如@Martti Laine在评论中提到的,以下代码只能起作用:
Bodies.rectangle(0, 0, 100, 100, {
render: {
fillStyle: 'red',
strokeStyle: 'blue',
lineWidth: 3
}
});
如果 render.options.wireframes
被设为 false
。
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: window.innerWidth,
height: window.innerHeight,
wireframes: false // <-- important
}
});
wireframes:false
。 - Organic Heart因为没有人回答关于如何改变画布背景颜色的问题,这部分可以像这样完成:
const Engine = Matter.Engine,
Render = Matter.Render,
World = Matter.World,
Bodies = Matter.Bodies;
// create an engine
const engine = Engine.create();
const render = Render.create({
element: document.body,
engine,
options: {
width: some_width,
height: some_height,
wireframes: false,
background: 'rgb(255,0,0)' // or '#ff0000' or other valid color string
}
})
现有的答案展示了如何对Matter.js的内置渲染器进行简单的颜色修改。这些答案很有用,但由于内置渲染器仅用于原型设计,尚未提供问题的通用解决方案。
Matter.js是一个物理引擎,而不是渲染库。它旨在成为您选择的任何渲染前端的无头后端。
我有很多帖子展示了如何在各种环境中使用它。浏览一下这些帖子应该会发现MJS的渲染限制反复出现,解决方法几乎总是“不要使用内置渲染器”。
通用方法:
使用DOM的解决方案:
如果您仍然不确定,这里有一个使用canvas和rough.js的示例,说明一旦您进入无头模式,您几乎可以按照自己的喜好进行样式和颜色的设置:
const renderRect = ({body, rect, w, h}) => {
const {x, y} = body.position;
ctx.save();
ctx.translate(x, y);
ctx.rotate(body.angle);
ctx.translate(-w / 2, -h / 2);
r.draw(rect);
ctx.restore();
};
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
const r = rough.canvas(canvas);
const engine = Matter.Engine.create();
const box = {
w: 40, h: 40,
body: Matter.Bodies.rectangle(150, 0, 40, 40),
rect: r.generator.rectangle(0, 0, 40, 40, {
fill: "red",
fillStyle: "solid",
roughness: 1.5,
hachureAngle: 45,
hachureGap: 7,
strokeWidth: 2,
}),
};
const ground = {
w: 400, h: 120,
body: Matter.Bodies.rectangle(
200, 200, 400, 120, {isStatic: true}
),
rect: r.generator.rectangle(0, 0, 400, 120, {
fill: "green",
fillStyle: "solid",
roughness: 1.5,
strokeWidth: 2,
}),
};
const mouseConstraint = Matter.MouseConstraint.create(
engine, {element: document.body}
);
Matter.Composite.add(
engine.world, [box.body, ground.body, mouseConstraint]
);
(function rerender() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
renderRect(ground);
renderRect(box);
Matter.Engine.update(engine);
requestAnimationFrame(rerender);
})();
body {
margin: 0;
background: #dda;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<script src="https://unpkg.com/roughjs@4.3.1/bundled/rough.js"></script>
<canvas width="700" height="400"></canvas>
#ff0000
)?将fillStyle
设置为#ff0000
或rgb(255,0,0)
根本不起作用。 - user4180960render.options.wireframes = false
。 - Martti Laine