最终效果图如下:
1. 弹幕从弹幕区域外的右边滚动到左边,那么每条弹幕的实际滚动路径长度为当前弹幕的实际宽度+整个弹幕区域的宽度
组件代码如下:
<template>
<view class="l-barrage">
<block v-for="(item,index) in items" :key="index">
<view
class="barrage-item"
:id="item.id"
:data-duration="item.duration"
:data-trackindex="item.trackIndex"
:style="{
top: `${
item.top}`,
'animation-duration': `${
Number(item.duration)}s`}"
@animationend="handleEnd(item.id, item.trackIndex)">
{
{
item.text}}
</view>
</block>
<!-- 计算每条弹幕实际的宽度 -->
<view class="bullet-container">{
{
currentBullet}}</view>
</view>
</template>
2. 本例中弹幕区域的宽度为当前屏幕的宽度。弹幕的滚动效果使用css3的animation实现,使用translateX来实现水平位移的变化。弹幕使用绝对定位初始时在屏幕的最左边(left: 0),动画开始时弹幕在屏幕外的右边,那么相对于弹幕区域的水平位移为100vw,动画结束时要滚动到屏幕外的左边,水平位移正好为负的当前弹幕的实际宽度。
样式代码如下:
<style lang="scss">
.l-barrage {
position: relative;
z-index: 3;
width: 100vw; // 弹幕区域的宽度为屏幕的宽度
height: 26vh; // 这里的高度可以根据实际需要显示弹幕的行数来设定,如每行高度为24px,那么我们可以设置大于
.barrage-item {
position: absolute;
left: 0;
padding: 0 16rpx;
white-space: nowrap;
color: #fff;
font-size: 30rpx;
background-color: rgba(#fff, .16);
border-radius: 20rpx;
animation: mymove 10s linear forwards;
}
.bullet-container {
position: absolute;
right: 9999rpx;
visibility: hidden;
white-space: nowrap;
}
}
@keyframes mymove
{
from{
transform: translateX(100vw);}
to{
transform: translateX(-100%);}
}
@-moz-keyframes mymove /* Firefox */
{
from{
transform: translateX(100vw);}
to{
transform: translateX(-100%);}
}
@-webkit-