Certainly! Below is an HTML code snippet that takes your SVG and makes it draggable. When you throw it, it will continue moving, bounce off the edges of the container, and rotate while in motion.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Draggable and Bouncing SVG</title>
<style>
body {
margin: 0;
overflow: hidden;
}
#container {
width: 100vw;
height: 100vh;
position: relative;
background-color: #f0f0f0;
}
#draggable {
position: absolute;
cursor: grab;
touch-action: none; /* Prevent touch scrolling while dragging */
}
</style>
</head>
<body>
<div id="container">
<svg
id="draggable"
xmlns="http://www.w3.org/2000/svg"
width="200"
height="200"
viewBox="0 0 200 200"
>
<!-- Outer Points -->
<polygon
points="100,10 110,70 180,70 120,100 150,170 100,130 50,170 80,100 20,70 90,70"
fill="#555"
stroke="#000"
stroke-width="2"
/>
<!-- Center Circle -->
<circle cx="100" cy="100" r="15" fill="#333" stroke="#000" stroke-width="2" />
</svg>
</div>
<script>
(function() {
const svg = document.getElementById('draggable');
const container = document.getElementById('container');
// Variables for dragging
let isDragging = false;
let lastX, lastY;
let offsetX, offsetY;
let velocityX = 0, velocityY = 0;
let lastTime = 0;
// Variables for animation
let animationFrameId;
// Variables for rotation
let rotation = 0;
let angularVelocity = 0;
// Set initial position
let posX = (window.innerWidth - svg.clientWidth) / 2;
let posY = (window.innerHeight - svg.clientHeight) / 2;
// Apply initial position
svg.style.left = posX + 'px';
svg.style.top = posY + 'px';
// Mouse events
svg.addEventListener('mousedown', startDrag);
document.addEventListener('mousemove', duringDrag);
document.addEventListener('mouseup', endDrag);
// Touch events
svg.addEventListener('touchstart', startDrag);
document.addEventListener('touchmove', duringDrag);
document.addEventListener('touchend', endDrag);
function startDrag(event) {
event.preventDefault();
isDragging = true;
svg.style.cursor = 'grabbing';
const rect = svg.getBoundingClientRect();
// For mouse or touch positions
let clientX, clientY;
if (event.touches) {
// Touch event
clientX = event.touches[0].clientX;
clientY = event.touches[0].clientY;
} else {
// Mouse event
clientX = event.clientX;
clientY = event.clientY;
}
offsetX = clientX - rect.left;
offsetY = clientY - rect.top;
lastX = clientX;
lastY = clientY;
lastTime = performance.now();
// Stop any ongoing animation
cancelAnimationFrame(animationFrameId);
}
function duringDrag(event) {
if (!isDragging) return;
event.preventDefault();
let clientX, clientY;
if (event.touches) {
clientX = event.touches[0].clientX;
clientY = event.touches[0].clientY;
} else {
clientX = event.clientX;
clientY = event.clientY;
}
// Update position
posX = clientX - offsetX;
posY = clientY - offsetY;
svg.style.left = posX + 'px';
svg.style.top = posY + 'px';
// Calculate velocity
const deltaX = clientX - lastX;
const deltaY = clientY - lastY;
const deltaTime = performance.now() - lastTime;
velocityX = deltaX / deltaTime * 16.67; // Normalize to per-frame velocity (~60fps)
velocityY = deltaY / deltaTime * 16.67;
// Calculate angular velocity based on movement
angularVelocity = (deltaX + deltaY) / 2;
lastX = clientX;
lastY = clientY;
lastTime = performance.now();
}
function endDrag(event) {
if (!isDragging) return;
isDragging = false;
svg.style.cursor = 'grab';
// Start animation
animationFrameId = requestAnimationFrame(updatePosition);
}
function updatePosition() {
const containerRect = container.getBoundingClientRect();
const svgRect = svg.getBoundingClientRect();
// Update position
posX += velocityX;
posY += velocityY;
// Update rotation
rotation += angularVelocity;
// Bounce off edges
if (posX <= 0) {
posX = 0;
velocityX = -velocityX * 0.8; // Reduce speed slightly to simulate energy loss
angularVelocity = -angularVelocity * 0.8;
}
if (posX + svgRect.width >= containerRect.width) {
posX = containerRect.width - svgRect.width;
velocityX = -velocityX * 0.8;
angularVelocity = -angularVelocity * 0.8;
}
if (posY <= 0) {
posY = 0;
velocityY = -velocityY * 0.8;
angularVelocity = -angularVelocity * 0.8;
}
if (posY + svgRect.height >= containerRect.height) {
posY = containerRect.height - svgRect.height;
velocityY = -velocityY * 0.8;
angularVelocity = -angularVelocity * 0.8;
}
// Apply friction
velocityX *= 0.98;
velocityY *= 0.98;
angularVelocity *= 0.98;
// Update SVG position
svg.style.left = posX + 'px';
svg.style.top = posY + 'px';
svg.style.transform = `rotate(${rotation}deg)`;
// Continue animation if speed is above a threshold
if (Math.abs(velocityX) > 0.1 || Math.abs(velocityY) > 0.1) {
animationFrameId = requestAnimationFrame(updatePosition);
}
}
// Adjust to window resize
window.addEventListener('resize', () => {
// Ensure the SVG stays within bounds
const containerRect = container.getBoundingClientRect();
const svgRect = svg.getBoundingClientRect();
if (posX + svgRect.width > containerRect.width) {
posX = containerRect.width - svgRect.width;
svg.style.left = posX + 'px';
}
if (posY + svgRect.height > containerRect.height) {
posY = containerRect.height - svgRect.height;
svg.style.top = posY + 'px';
}
});
})();
</script>
</body>
</html>
How It Works:
-
Dragging Mechanism: The code listens for mousedown, mousemove, and mouseup events to handle dragging. For touch devices, it also listens to touchstart, touchmove, and touchend.
-
Calculating Velocity: While dragging, it calculates the velocity based on the movement and time between events. This simulates how fast the user "throws" the SVG.
-
Animating Movement: After the user releases the SVG, it continues to move based on the calculated velocity. The requestAnimationFrame function is used for smooth animations.
-
Bouncing Off Edges: The code checks for collisions with the container's edges. When the SVG hits an edge, it reverses its velocity on that axis and reduces it slightly to simulate energy loss.
-
Rotation: The SVG rotates while moving. The rotation speed is proportional to the dragging speed, giving a more realistic "throwing" effect.
-
Friction: Gradually reduces the velocity and angular velocity to simulate friction, eventually bringing the SVG to a stop.
Notes:
-
Styling: The cursor: grab and cursor: grabbing styles provide visual feedback to the user.
-
Touch Support: The code includes support for touch events, making it work on mobile devices.
-
Adjustable Parameters: You can tweak the friction (velocityX *= 0.98) and energy loss on bounce (velocityX = -velocityX * 0.8) to change how the SVG moves.
Demo:
To see this in action:
- Copy the entire code above into a text editor.
- Save the file with a
.html extension (e.g., drag-throw-bounce.svg.html).
- Open the file in a modern web browser (such as Chrome, Firefox, or Edge).
Customization:
-
Changing the SVG: Replace the SVG content inside the <svg> tags with any other SVG content if desired.
-
Container Size: Currently, the container takes up the full viewport (100vw and 100vh). You can adjust the size and positioning as needed.
-
Adding More Elements: If you wish to have multiple draggable SVGs, you'll need to adjust the code to handle multiple elements, possibly using classes instead of IDs.
Troubleshooting:
-
Not Moving After Release: Ensure that the velocity is being calculated correctly during the drag. Check the console for any errors.
-
SVG Disappears: If the SVG goes off-screen and doesn't come back, make sure the bounce logic correctly positions the SVG within the container bounds.
-
Performance Issues: For lower-powered devices, heavy SVGs or complex animations might cause performance issues. Simplify the SVG or reduce the animation updates if necessary.
Further Enhancements:
-
Elasticity: Adjust the bounce effect to be more elastic or stiff by modifying the velocity dampening factor.
-
Boundaries: Implement more complex boundary rules, like wrapping around the screen edges.
-
Collision Detection: If you have multiple SVGs, implement collision detection between them.
Feel free to ask if you have any questions or need further assistance!