当前位置:首页 > VUE

Vue实现弹幕漂浮效果

2026-01-07 04:05:01VUE

Vue实现弹幕弹幕漂浮效果

核心思路
通过动态生成弹幕DOM元素,利用CSS动画或JavaScript控制其从右向左移动,并通过Vue的数据驱动特性管理弹幕生命周期。

基础实现步骤

创建弹幕组件
定义单条弹幕的模板和样式,包含文字内容、颜色、速度等属性。

Vue实现弹幕漂浮效果

<template>
  <div class="danmu-item" :style="style">
    {{ text }}
  </div>
</template>

<script>
export default {
  props: ['text', 'color', 'speed'],
  computed: {
    style() {
      return {
        color: this.color,
        animationDuration: `${this.speed}s`
      };
    }
  }
};
</script>

<style>
.danmu-item {
  position: absolute;
  white-space: nowrap;
  animation: move linear;
}

@keyframes move {
  from { transform: translateX(100vw); }
  to { transform: translateX(-100%); }
}
</style>

管理弹幕队列
在父组件中使用数组存储弹幕数据,通过定时器动态添加新弹幕并清理过期弹幕。

<template>
  <div class="danmu-container">
    <DanmuItem 
      v-for="(item, index) in danmuList" 
      :key="index"
      :text="item.text"
      :color="item.color"
      :speed="item.speed"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {
      danmuList: [],
      colors: ['#ff0000', '#00ff00', '#0000ff']
    };
  },
  methods: {
    addDanmu(text) {
      this.danmuList.push({
        text,
        color: this.colors[Math.floor(Math.random() * 3)],
        speed: 5 + Math.random() * 5
      });
    }
  }
};
</script>

进阶优化方案

性能优化
使用requestAnimationFrame替代CSS动画,手动控制弹幕位置以减少重绘开销。

Vue实现弹幕漂浮效果

updatePosition() {
  this.danmuList.forEach(item => {
    item.x -= 2;
    if (item.x < -item.width) this.removeDanmu(item);
  });
  requestAnimationFrame(this.updatePosition);
}

碰撞检测
通过计算弹幕的Y轴位置和高度,避免重叠显示。

getRandomY() {
  const y = Math.random() * (containerHeight - danmuHeight);
  return this.isOverlap(y) ? this.getRandomY() : y;
}

互动功能
添加点击事件暂停或加速特定弹幕。

<div @click="handleClick(item)">{{ item.text }}</div>

handleClick(item) {
  item.speed = item.speed > 1 ? 0 : 5;
}

完整示例代码

查看CodePen示例(模拟链接)
包含:随机颜色、速度控制、自动清理、响应式布局等功能实现。

标签: 效果弹幕
分享给朋友:

相关文章

vue弹幕实现不重叠

vue弹幕实现不重叠

实现 Vue 弹幕不重叠的方法 CSS 定位与动画控制 通过绝对定位和动态计算弹幕轨道高度,确保弹幕在不同轨道上运行。每条弹幕占据固定高度的轨道,避免重叠。 // 弹幕轨道高度计算 const t…

vue 实现弹幕

vue 实现弹幕

vue 实现弹幕的方法 使用 CSS 动画和动态渲染 在 Vue 中实现弹幕效果,可以通过动态渲染弹幕元素并结合 CSS 动画实现。以下是具体步骤: 数据准备 创建一个数组存储弹幕数据,每条弹幕…

vue实现效果

vue实现效果

以下是Vue实现常见效果的几种典型方法,分为不同场景说明: 数据绑定与响应式更新 使用v-model实现表单双向绑定: <template> <input v-model…

vue实现弹幕

vue实现弹幕

Vue 实现弹幕功能 弹幕功能通常包括动态生成、滚动显示、颜色和速度随机化等特性。以下是基于 Vue 3 的实现方法。 核心思路 使用 CSS 动画控制弹幕从右向左滚动。 动态生成弹幕数据,随机设…

vue实现翻页效果

vue实现翻页效果

Vue实现翻页效果的方法 使用v-for和计算属性 通过计算属性动态计算当前页显示的数据,结合v-for渲染分页内容。定义currentPage和pageSize控制分页逻辑。 <templ…