Recently, I implemented a Vue component designed to loop a div over the X axis. While it functions correctly, I can't help but notice that it is consuming an excessive amount of CPU. I am interested in optimizing this animation for better performance. The galleryItems are supposed to move along the x-axis and when they reach the width of their parent div, they should disappear from one side and reappear on the other side to continue the loop seamlessly. Ideally, I would like to achieve this optimization without relying on external plugins.
<template>
<div class="placeholder">
<div class="gallery" ref="gallery">
<div class="gallery-item" v-for="i in 10" :key="i" ref="galleryItems" />
</div>
</div>
</template>
<script>
export default {
props:{
xoffset : {
type: Number,
default: 0,
},
speed : {
type: Number,
default: 1,
},
spaceBetween : {
type: Number,
default: 50,
},
},
data() {
return {
}
},
mounted(){
for(let i = 0; i < this.$refs.galleryItems.length; i++)
this.$refs.galleryItems[i].style.transform = 'translateX(' + (this.$refs.galleryItems[i].clientWidth + this.spaceBetween) * i + 'px)';
this.animate();
},
methods:{
animate(){
window.requestAnimationFrame(this.animate);
for(let i = 0; i < this.$refs.galleryItems.length; i++)
{
let galleryItemRect = this.$refs.galleryItems[i].getBoundingClientRect();
if(galleryItemRect.x > this.$refs.gallery.clientWidth)
{
this.$refs.galleryItems[i].style.transform = 'translateX(' + -galleryItemRect.width + 'px)';
continue;
}
this.$refs.galleryItems[i].style.transform = 'translateX(' + (galleryItemRect.x + this.speed) + 'px)';
}
}
}
}
</script>
<style lang="scss" scoped>
.placeholder{
height: 100vh;
display: flex;
align-items: center;
}
.gallery
{
position: relative;
background-color: green;
height: 100px;
width: 100%;
overflow: hidden;
}
.gallery-item{
display: block;
position: absolute;
background-color: black;
height: inherit;
min-width: 100px;
transition: 0s;
}
</style>