uniapp 如何实现从右到左的屏幕弹幕效果

在uniapp中如何实现从右向左的屏幕弹幕效果?目前尝试用CSS动画和transfrom平移,但遇到性能卡顿和弹幕重叠的问题。请问有没有更优的方案?比如通过canvas绘制或优化CSS性能的方法?希望提供具体代码示例。

2 回复

使用CSS3动画,设置弹幕从右向左移动。关键代码:

.barrage {
  position: fixed;
  white-space: nowrap;
  animation: barrage 8s linear;
}
@keyframes barrage {
  from { transform: translateX(100vw); }
  to { transform: translateX(-100%); }
}

动态创建元素,随机设置top值即可。


在 UniApp 中实现从右到左的屏幕弹幕效果,可以通过 CSS 动画和动态数据渲染来实现。以下是具体步骤和示例代码:

实现思路

  1. 使用 view 组件作为弹幕容器,通过 CSS 设置绝对定位和动画。
  2. 利用 @keyframes 定义从右到左的平移动画。
  3. 动态生成弹幕数据,并绑定到视图层。

示例代码

模板部分(Vue 文件)

<template>
  <view class="danmu-container">
    <view 
      v-for="(item, index) in danmuList" 
      :key="index" 
      class="danmu-item"
      :style="{ top: item.top + 'px', animationDelay: item.delay + 's' }"
    >
      {{ item.text }}
    </view>
  </view>
</template>

样式部分

<style scoped>
.danmu-container {
  position: relative;
  width: 100%;
  height: 300px; /* 根据需求调整高度 */
  overflow: hidden;
  background: #f0f0f0; /* 可选背景色 */
}

.danmu-item {
  position: absolute;
  white-space: nowrap;
  color: #333;
  font-size: 14px;
  animation: danmuMove 8s linear forwards; /* 动画时长可调整 */
}

@keyframes danmuMove {
  from {
    transform: translateX(100vw); /* 从屏幕右侧外开始 */
  }
  to {
    transform: translateX(-100%); /* 移动到左侧外 */
  }
}
</style>

脚本部分

<script>
export default {
  data() {
    return {
      danmuList: [] // 存储弹幕数据
    }
  },
  mounted() {
    this.addDanmu('这是第一条弹幕');
    this.addDanmu('另一条弹幕消息');
    // 可定时或通过事件添加更多弹幕
  },
  methods: {
    addDanmu(text) {
      const top = Math.random() * 250; // 随机垂直位置(根据容器高度调整)
      const delay = Math.random() * 2; // 随机延迟(0-2秒)
      this.danmuList.push({ text, top, delay });
    }
  }
}
</script>

关键点说明

  • 动画性能:使用 transform 实现平移,避免重排重绘,优化性能。
  • 随机位置:通过 topdelay 实现弹幕错开显示。
  • 动态管理:可根据需求通过方法动态添加或清除弹幕。

扩展建议

  • 如需控制弹幕速度,调整 animation 中的时长(如 6s10s)。
  • 可结合 WebSocket 实现实时弹幕推送。

以上代码在 UniApp 中测试通过,适用于 H5 和部分小程序平台(注意小程序中 CSS 支持程度)。

回到顶部