You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中使用Rive动画动态渲染星空背景的问题排查

Vue + Rive 星空背景动态渲染问题排查与修复

问题场景

在Vue项目中开发全屏星空背景,用Rive制作星星动画并封装为独立组件,计划通过生成带随机位置的星星列表,用v-for循环渲染实现动态分布效果。但实际运行后,仅在页面左上角显示一颗星星,静态画布绘制星星的功能正常,问题集中在动态生成的逻辑环节。

排查过程

排查后定位两个核心问题:

  • v-for缺少唯一标识符:循环渲染星星组件时未绑定唯一key值,Vue虚拟DOM复用机制导致所有星星组件被复用为同一个,仅显示最后一个生成的星星(位置默认左上角)。
  • CSS布局疏漏:星星组件未设置正确的绝对定位,无法基于全屏容器的相对定位来应用随机位置参数。

修复方案

  1. 添加唯一ID标识:给每个星星对象生成唯一ID(自增序号或UUID均可),在v-for中通过:key="star.id"绑定,确保Vue能正确区分每个组件实例。
  2. 调整CSS定位:给全屏容器设置position: fixed或relative,星星组件设置position: absolute,通过left和top的百分比值实现随机位置分布。

修复后代码示例

星空页面组件

<template>
  <div class="star-sky-container">
    <StarComponent 
      v-for="star in starsList" 
      :key="star.id" 
      :position="star.position"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import StarComponent from './StarComponent.vue'

const starsList = ref([])

onMounted(() => {
  // 生成100个带唯一ID和随机位置的星星
  for (let i = 0; i < 100; i++) {
    starsList.value.push({
      id: `star-${i}`,
      position: {
        x: Math.random() * 100,
        y: Math.random() * 100
      }
    })
  }
})
</script>

<style scoped>
.star-sky-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}
</style>

星星动画组件

<template>
  <div class="star-item" :style="{ left: `${position.x}%`, top: `${position.y}%` }">
    <canvas ref="starCanvas"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Rive from 'rive-js'

const props = defineProps({
  position: {
    type: Object,
    required: true
  }
})

const starCanvas = ref(null)

onMounted(() => {
  new Rive({
    src: '/star-animation.riv',
    canvas: starCanvas.value,
    autoplay: true
  })
})
</script>

<style scoped>
.star-item {
  position: absolute;
  width: 20px;
  height: 20px;
}
</style>

内容的提问来源于stack exchange,提问作者JUSTICE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 15:22:20