我想用Matter.js来移动HTML元素,方法如下 这个.
这些都是我的目标。
div {
color: white;
font-size: 70px;
padding: 20px;
display: inline-block;
font-family: Arial;
background: azure;
}
.canvas {
width: 500px;
height: 500px;
}
.object-one {
background: blue;
}
.object-two {
background: red;
}
.object-three {
background: green;
}
<script src="https://raw.githubusercontent.com/liabru/matter-js/master/build/matter.js"></script>
<div class="canvas">
<div class="object-one">One</div>
<div class="object-two">Two</div>
<div class="object-three">Three</div>
</div>
它是在一般情况下可能吗?谁能帮帮我?)
我的网站 是用 matter.js 构建的。我的方法是根据物质体的变换来变换我的DOM元素,在 update()
功能。
var bodiesDom = document.querySelectorAll('.matter-body');
var bodies = [];
for (var i = 0, l = bodiesDom.length; i < l; i++) {
if (bodiesDom[i].classList.contains('hot')) {
frA = 0.1;
oY = -40;
} else {
frA = 0;
oY = 0;
}
if (bodiesDom[i].classList.contains('strip')) {
// Strip
var body = Bodies.rectangle(
VIEW.centerX + Math.floor(Math.random() * VIEW.width/2) - VIEW.width/4,
oY,
VIEW.width * bodiesDom[i].offsetWidth / window.innerWidth,
VIEW.height * bodiesDom[i].offsetHeight / window.innerHeight, {
restitution: 0.05,
friction: 2,
frictionAir: frA,
frictionStatic: 20,
density: 100,
chamfer: { radius: 4 },
angle: (Math.random() * 2.000) - 1.000
}
);
} else if (bodiesDom[i].classList.contains('page-nav')) {
// Nav
var body = Bodies.circle(
VIEW.centerX + Math.floor(Math.random() * VIEW.width/2) - VIEW.width/4,
0,
24, {
restitution: 0.3,
friction: 2,
frictionAir: 0,
frictionStatic: 2,
density: 100,
angle: (Math.random() * 2.000) - 1.000
}
);
}
bodiesDom[i].id = body.id;
bodies.push(body);
}
function update() {
// strips
for (var i = 0, l = bodiesDom.length; i < l; i++) {
var bodyDom = bodiesDom[i];
var body = null;
for (var j = 0, k = bodies.length; j < k; j++) {
if (bodies[j].id == bodyDom.id) {
body = bodies[j];
break;
}
}
if (body === null) continue;
bodyDom.style.transform = "translate( " +
(body.position.x - bodyDom.offsetWidth / 2) +
"px, " +
(body.position.y - bodyDom.offsetHeight / 2) +
"px )";
bodyDom.style.transform += "rotate( " + body.angle + "rad )";
}
window.requestAnimationFrame(update);
}
代码在 https:/github.comaentanaenism2bmasterstrombaticsrcjsmain.js。