Created
January 10, 2024 18:38
-
-
Save ejfox/763ba7f07e8363d1ed2e426d9e34c9e4 to your computer and use it in GitHub Desktop.
Tween the positions of circles using vueUse's useTween composable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script setup> | |
import { ref } from 'vue' | |
import { useTween } from '@vueuse/core' | |
// Let's assume each circle has an initial x and y position | |
const circles = ref([ | |
{ id: 1, x: 100, y: 100 }, | |
{ id: 2, x: 150, y: 200 }, | |
// Add as many circles as you want | |
]) | |
// Function to create tween for circle positions | |
function createTweenedPositions(circle) { | |
// Create reactive properties with tween for x and y | |
return { | |
x: useTween(ref(circle.x), { duration: 2000 }), | |
y: useTween(ref(circle.y), { duration: 2000 }), | |
} | |
} | |
// Map each circle to have tweened x and y | |
const animatedCircles = circles.value.map((circle) => ({ | |
...circle, | |
...createTweenedPositions(circle), | |
})) | |
// Function to update positions and start the animation | |
function updatePositions(newPositions) { | |
newPositions.forEach((pos, index) => { | |
// Update the target values for tween | |
circles.value[index].x = pos.x | |
circles.value[index].y = pos.y | |
// Trigger the animation | |
animatedCircles[index].x.value = pos.x | |
animatedCircles[index].y.value = pos.y | |
}); | |
} | |
// Example usage: Move circles to new positions | |
updatePositions([ | |
{ x: 200, y: 100 }, | |
{ x: 100, y: 300 }, | |
// Match new positions to your circles | |
]) | |
</script> | |
<template> | |
<svg> | |
<circle | |
v-for="circle in animatedCircles" | |
:key="circle.id" | |
:cx="circle.x" | |
:cy="circle.y" | |
r="10" | |
fill="blue" | |
/> | |
</svg> | |
</template> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment