Skip to content

Instantly share code, notes, and snippets.

@mwdchang
Created December 22, 2022 02:32
Show Gist options
  • Save mwdchang/a275dd5f878ee1c6453133cc80f49400 to your computer and use it in GitHub Desktop.
Save mwdchang/a275dd5f878ee1c6453133cc80f49400 to your computer and use it in GitHub Desktop.
Mixing MatterJS with D3JS
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.18.0/matter.min.js" integrity="sha512-5T245ZTH0m0RfONiFm2NF0zcYcmAuNzcGyPSQ18j8Bs5Pbfhp5HP1hosrR8XRt5M3kSRqzjNMYpm2+it/AUX/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.0/d3.min.js" integrity="sha512-jXsLjbg/Pr8F5U2evjFaEci7mImlUix865lbvnNmp5TzS86+VTTFVDz7FFTS6VHdhSn7UJ4tjZdvpp0GgT0fZA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<svg id="svg" style="width: 100%; height: 100%"></svg>
</body>
<script>
const Engine = Matter.Engine;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
const Composite = Matter.Composite;
const svg = d3.select('#svg');
const engine = Engine.create();
const group = Body.nextGroup(true);
const boxA = Bodies.rectangle(400, 50, 80, 80, { stiffness: 0.3, friction: 0.8, frictionAir: 0.1 });
const boxB = Bodies.rectangle(450, 150, 80, 80, { stiffness: 0.3, friction: 0.8, frictionAir: 0.1 });
// Disable gravity
engine.world.gravity.y = 0;
// Initialize
Composite.add(engine.world, [boxA, boxB]);
const bodies = Composite.allBodies(engine.world);
const useForce = true;
for (const obj of bodies) {
const pos = obj.position;
svg.append('rect')
.datum(obj)
.attr('id', `box-${obj.id}`)
.attr('x', pos.x)
.attr('y', pos.y)
.attr('width', 80)
.attr('height', 80)
.attr('fill', '#f80');
}
d3.selectAll('rect').call(d3.drag()
.on('start', () => {})
.on('drag', (event, d) => {
const { x, y } = d.position;
if (useForce) {
const nX = x + event.dx;
const nY = y + event.dy;
Matter.Body.applyForce(d, { x: nX, y: nY }, { x: (nX - x)/500, y: (nY - y)/500 });
} else {
Matter.Body.setPosition(d, { x: x + event.dx, y: y + event.dy });
}
})
.on('end', () => {
})
);
// const mouse = Matter.Mouse.create(document.querySelector('#svg'));
//
// const mouseConstraint = Matter.MouseConstraint.create(
// engine, { element: document.querySelector('#box-1') }
// );
// Composite.add(engine.world, [mouseConstraint]);
//
// Matter.Events.on(mouseConstraint, 'startdrag', (x) => {
// console.log('debugging', x.source);
// });
// Matter.Events.on(mouseConstraint, 'mousedown', (x) => {
// console.log('debugging', x.source);
// });
(function run() {
window.requestAnimationFrame(run);
Engine.update(engine, 1000 / 60);
for (const obj of bodies) {
// console.log(obj.position, svg.select(`#box-${obj.id}`));
svg.select(`#box-${obj.id}`)
.attr('x', obj.position.x)
.attr('y', obj.position.y);
}
})();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment