Write a line in HTML (without relying on canvas), and give it bones and add gravity to look realistic and make its two points (left and right) draggable with the with the mouse cursor. Make sure to simulate real-life physics
Assistant
Certainly! Below is an HTML code snippet that creates a line with "bones" and simulates real-life physics, including gravity. The two endpoints of the line are draggable with the mouse cursor. This implementation uses plain HTML, CSS, and JavaScript without relying on the <canvas> element. The physics simulation is achieved through Verlet integration and constraint relaxation to simulate a rope-like behavior.
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Interactive Physics Line</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #222;
}
#container {
position: relative;
width: 100vw;
height: 100vh;
touch-action: none;
}
.node {
position: absolute;
width: 6px;
height: 6px;
background-color: #fff;
border-radius: 50%;
pointer-events: none;
}
.stick {
position: absolute;
height: 2px;
background-color: #fff;
pointer-events: none;
transform-origin: top left;
}
.draggable {
pointer-events: auto;
cursor: grab;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
// Get the container element
const container = document.getElementById('container');
// Constants for simulation
const NUM_NODES = 20; // Number of nodes in the line
const GRAVITY = 0.5; // Gravity acceleration
const FRICTION = 0.99; // Friction coefficient
const BOUNCE = 0.9; // Bounce coefficient for edges
// Arrays to hold nodes and sticks
const nodes = [];
const sticks = [];
// Mouse state
const mouse = {
x: 0,
y: 0,
isDown: false,
node: null,
offsetX: 0,
offsetY: 0,
};
// Create nodes
for(let i = 0; i < NUM_NODES; i++) {
const node = {
x: 300 + i * 15, // Initial x position
y: 100, // Initial y position
oldx: 300 + i * 15, // Previous x position for Verlet
oldy: 100, // Previous y position for Verlet
element: document.createElement('div')
};
node.element.classList.add('node');
container.appendChild(node.element);
nodes.push(node);
}
// Make first and last node draggable
nodes[0].element.classList.add('draggable');
nodes[NUM_NODES - 1].element.classList.add('draggable');
// Create sticks (constraints) between nodes
for(let i = 0; i < NUM_NODES - 1; i++) {
const stick = {
p0: nodes[i],
p1: nodes[i + 1],
length: 15, // Desired length between nodes
element: document.createElement('div')
};
stick.element.classList.add('stick');
container.appendChild(stick.element);
sticks.push(stick);
}
// Physics simulation function
function physics() {
// Apply gravity and integrate motion
for(let i = 1; i < NUM_NODES - 1; i++) {
let node = nodes[i];
const vx = (node.x - node.oldx) * FRICTION;
const vy = (node.y - node.oldy) * FRICTION;
node.oldx = node.x;
node.oldy = node.y;
node.x += vx;
node.y += vy + GRAVITY;
}
// Satisfy constraints (maintain stick lengths)
for(let i = 0; i < 5; i++) { // Iterate multiple times for stability
for(let s of sticks) {
const dx = s.p1.x - s.p0.x;
const dy = s.p1.y - s.p0.y;
const dist = Math.sqrt(dx * dx + dy * dy);
const diff = s.length - dist;
const percent = diff / dist / 2;
const offsetX = dx * percent;
const offsetY = dy * percent;
if(s.p0 !== mouse.node) {
s.p0.x -= offsetX;
s.p0.y -= offsetY;
}
if(s.p1 !== mouse.node) {
s.p1.x += offsetX;
s.p1.y += offsetY;
}
}
// Keep nodes within container bounds
for(let node of nodes) {
if(node !== nodes[0] && node !== nodes[NUM_NODES - 1]) {
const vx = (node.x - node.oldx) * FRICTION;
const vy = (node.y - node.oldy) * FRICTION;
if(node.x > container.clientWidth) {
node.x = container.clientWidth;
node.oldx = node.x + vx * BOUNCE;
} else if(node.x < 0) {
node.x = 0;
node.oldx = node.x + vx * BOUNCE;
}
if(node.y > container.clientHeight) {
node.y = container.clientHeight;
node.oldy = node.y + vy * BOUNCE;
} else if(node.y < 0) {
node.y = 0;
node.oldy = node.y + vy * BOUNCE;
}
}
}
}
}
// Render function to update the DOM elements
function render() {
// Render nodes
for(let node of nodes) {
node.element.style.transform = `translate(${node.x - 3}px, ${node.y - 3}px)`;
}
// Render sticks
for(let stick of sticks) {
const dx = stick.p1.x - stick.p0.x;
const dy = stick.p1.y - stick.p0.y;
const length = Math.sqrt(dx * dx + dy * dy);
stick.element.style.width = `${length}px`;
const angle = Math.atan2(dy, dx) * 180 / Math.PI;
stick.element.style.transform = `translate(${stick.p0.x}px, ${stick.p0.y}px) rotate(${angle}deg)`;
}
}
// Animation loop
function animate() {
requestAnimationFrame(animate);
physics();
render();
}
// Mouse Events for dragging
container.addEventListener('mousedown', function(e) {
mouse.x = e.clientX;
mouse.y = e.clientY;
// Check if mouse is over a draggable node
for(let node of [nodes[0], nodes[NUM_NODES - 1]]) {
const rect = node.element.getBoundingClientRect();
if(e.clientX >= rect.left && e.clientX <= rect.right &&
e.clientY >= rect.top && e.clientY <= rect.bottom) {
mouse.isDown = true;
mouse.node = node;
mouse.offsetX = e.clientX - node.x;
mouse.offsetY = e.clientY - node.y;
break;
}
}
});
window.addEventListener('mousemove', function(e) {
if(mouse.isDown && mouse.node) {
mouse.x = e.clientX;
mouse.y = e.clientY;
mouse.node.x = mouse.x - mouse.offsetX;
mouse.node.y = mouse.y - mouse.offsetY;
}
});
window.addEventListener('mouseup', function(e) {
mouse.isDown = false;
mouse.node = null;
});
// Prevent default touch actions
container.addEventListener('touchstart', function(e) { e.preventDefault(); });
container.addEventListener('touchmove', function(e) { e.preventDefault(); });
// Start the animation
animate();
</script>
</body>
</html>
Explanation:
HTML Structure:
The #container div serves as the canvas for our simulation.
Nodes and sticks are dynamically added as child elements of the container.
CSS Styles:
Nodes are styled as small circles (.node) using absolute positioning.
Sticks are styled as thin rectangles (.stick) and rotated to connect nodes.
The .draggable class adds a cursor indicator and enables pointer events for the endpoints.
JavaScript Logic:
Nodes and Sticks Initialization:
Nodes represent points along the line, each with a current and previous position for simulating physics.
Sticks act as constraints (or "bones") to keep nodes at a fixed distance, simulating the rigidity of the line.
Physics Simulation:
Uses Verlet integration for smoother and more accurate physics.
Gravity is applied by adjusting the y-position of each node.
Constraints are resolved by adjusting node positions so that the distance between them equals the stick length.
Rendering:
Positions of nodes and sticks are updated by setting CSS transform properties.
Interactivity:
Mouse event listeners (mousedown, mousemove, mouseup) enable dragging of the endpoints.
When an endpoint is dragged, its position is directly updated, and physics calculations adjust the rest of the line accordingly.
Instructions to Use:
Running the Code:
Copy the entire code above into a text editor.
Save the file with an .html extension (e.g., interactive_line.html).
Open the file in a modern web browser (e.g., Chrome, Firefox, Edge).
Interacting with the Line:
Click and drag either endpoint (the small circles at both ends of the line).
Release the mouse button to drop the endpoint.
Observe how the line reacts to gravity and moves realistically.
Modifying the Simulation (Optional):
Adjust the Number of Nodes:
Change the NUM_NODES constant in the script to add or remove segments from the line.
Change Gravity or Friction:
Modify the GRAVITY and FRICTION constants to see how the line's behavior changes.
Styling:
Customize the appearance by editing CSS styles for .node and .stick.
Note: This implementation avoids using the <canvas> element and relies solely on standard HTML elements and CSS transformations for rendering. The physics simulation is simplified and intended for demonstration purposes. For more advanced physics simulations, consider using physics libraries or more complex algorithms.