Certainly! Below is an example of how to create a Matter.js simulation with a grey floor, where you can spawn cubes that display the image from the provided URL, and drag them around interactively.
Complete Code:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Matter.js Simulation with Draggable Cubes</title>
<style>
body {
margin: 0;
overflow: hidden; /* Hide scrollbars */
}
canvas {
display: block; /* Remove gaps around canvas */
}
</style>
</head>
<body>
<!-- Include Matter.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<script>
// Module aliases for easier access
const Engine = Matter.Engine,
Render = Matter.Render,
World = Matter.World,
Bodies = Matter.Bodies,
Body = Matter.Body,
Events = Matter.Events,
Mouse = Matter.Mouse,
MouseConstraint = Matter.MouseConstraint,
Composite = Matter.Composite;
// Create an engine
const engine = Engine.create();
const world = engine.world;
// Create a renderer
const render = Render.create({
element: document.body,
engine: engine,
options: {
width: window.innerWidth,
height: window.innerHeight,
background: '#ffffff',
wireframes: false,
pixelRatio: window.devicePixelRatio
}
});
// Run the renderer
Render.run(render);
// Create runner
const runner = Engine.run(engine);
// Add a grey floor
const floor = Bodies.rectangle(
window.innerWidth / 2,
window.innerHeight - 25,
window.innerWidth,
50,
{
isStatic: true,
render: {
fillStyle: '#808080'
}
}
);
World.add(world, floor);
// Function to spawn a cube with a sprite image
function spawnCube(x, y) {
const size = 60; // Size of the cube
const cube = Bodies.rectangle(x, y, size, size, {
render: {
sprite: {
texture: 'https://file.garden/ZwbDngbLgEb9w6CD/kitty.png',
xScale: size / 512, // Scale based on original image size
yScale: size / 512
}
}
});
World.add(world, cube);
}
// Add mouse control
const mouse = Mouse.create(render.canvas);
const mouseConstraint = MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
stiffness: 0.1,
render: {
visible: false
}
}
});
World.add(world, mouseConstraint);
// Keep the mouse in sync with rendering
render.mouse = mouse;
// Add an event listener for mouse clicks to spawn cubes
document.addEventListener('mousedown', function(event) {
const rect = render.canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
spawnCube(x, y);
});
// Handle window resize
window.addEventListener('resize', function() {
const width = window.innerWidth;
const height = window.innerHeight;
render.canvas.width = width;
render.canvas.height = height;
// Update floor position and size
Body.setPosition(floor, { x: width / 2, y: height - 25 });
Body.setVertices(floor, [
{ x: 0, y: height },
{ x: width, y: height },
{ x: width, y: height - 50 },
{ x: 0, y: height - 50 }
]);
});
</script>
</body>
</html>
Explanation:
Including Matter.js:
We include Matter.js via a CDN link in the <script> tag.
Creating the Physics Engine and Renderer:
The Engine.create() method sets up the physics engine.
Render.create() sets up the rendering context, matching the canvas size to the window size.
Adding a Grey Floor:
A static rectangle body is created to serve as the floor.
Positioned at the bottom of the viewport.
Styled with a grey color using render.fillStyle.
Spawning Cubes with an Image:
The spawnCube(x, y) function creates a new rectangle body at the provided coordinates.
The render.sprite.texture property applies the image to the body.
xScale and yScale adjust the image size to fit the cube.
Mouse Control and Dragging:
Mouse.create(render.canvas) captures mouse input on the canvas.
MouseConstraint.create(engine, { ... }) allows for dragging bodies with the mouse.
The mouse constraint is added to the world for interactivity.
Event Listener to Spawn Cubes:
An event listener for 'mousedown' is added to the document.
On click, it calculates the mouse position relative to the canvas.
Calls spawnCube(x, y) to create a new cube at the mouse position.
Handling Window Resizing:
An event listener for 'resize' adjusts the canvas size.
Updates the floor's position and vertices to match the new window size.
Notes:
CORS Considerations:
When using images from external URLs, ensure the server allows cross-origin requests.
If you encounter image loading issues, you might need to host the image on a server with appropriate CORS headers or use a local image.
Adjusting the Cube Size and Image Scaling:
The size variable controls the dimensions of the cubes.
Adjust xScale and yScale in the sprite settings to match the cube size to the image dimensions.
Replace 512 with the original width/height of the image if it's different.
Improving User Experience:
You can add borders or walls to prevent cubes from falling off the edges.
Implement additional controls or buttons to clear cubes or change the image.
Demo:
To see the simulation in action:
Copy the code into an HTML file (e.g., index.html).
Open the file in a modern web browser (e.g., Chrome, Firefox).
Click anywhere on the canvas to spawn a cube with the kitty image.
Click and drag to interact with the cubes.
Troubleshooting:
Image Not Showing:
If the kitty image doesn't appear on the cubes, check the browser console for CORS errors.
Verify that the image URL is correct and accessible.
Performance Issues:
Spawning a large number of cubes may slow down the simulation.
Optimize by limiting the number of active bodies or increasing stiffness in the mouse constraint.