danmakuManager.vue 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. <template>
  2. <view class="danmaku-container" :style="{ height: height + 'px' }">
  3. <view class="danmaku-stage">
  4. <view
  5. v-for="item in visibleDanmakus"
  6. :key="item.id"
  7. class="danmaku-item"
  8. :class="[`danmaku-track`, { 'danmaku-scrolling': item.isScrolling }]"
  9. :style="getDanmakuStyle(item)"
  10. >
  11. <view class="danmaku-content">
  12. <image class="danmaku-avatar" :src="item.icon || defaultAvatar" mode="aspectFill"></image>
  13. <view class="danmaku-text">{{ item.msg }}</view>
  14. </view>
  15. </view>
  16. </view>
  17. </view>
  18. </template>
  19. <script setup>
  20. import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
  21. const props = defineProps({
  22. danmakuList: {
  23. type: Array,
  24. default: () => []
  25. },
  26. height: {
  27. type: Number,
  28. default: 200
  29. },
  30. infinite: {
  31. type: Boolean,
  32. default: true
  33. },
  34. speed: {
  35. type: Number,
  36. default: 100
  37. },
  38. trackCount: {
  39. type: Number,
  40. default: 8
  41. },
  42. spacing: {
  43. type: Number,
  44. default: 20
  45. }
  46. })
  47. const emit = defineEmits(['danmakuComplete'])
  48. const visibleDanmakus = ref([])
  49. const animationTimer = ref(null)
  50. const danmakuIdCounter = ref(0)
  51. const trackOccupancy = ref(new Array(props.trackCount).fill(0)) // 记录每个轨道的占用情况
  52. // 监听trackCount变化,重新初始化trackOccupancy
  53. watch(() => props.trackCount, (newCount) => {
  54. trackOccupancy.value = new Array(newCount).fill(0)
  55. })
  56. const trackHeight = computed(() => props.height / props.trackCount)
  57. // 默认头像
  58. const defaultAvatar = 'https://birdseye-img.sysuimars.com/youwei-uniapp/img/default-avatar.png'
  59. const getDanmakuStyle = (danmaku) => {
  60. // 获取屏幕宽度,兼容不同平台
  61. const screenWidth = uni.getSystemInfoSync().screenWidth || 375
  62. // 增加更多的额外距离确保弹幕完全离开可视范围
  63. const extraDistance = 200 // 增加缓冲距离
  64. const duration = (screenWidth + danmaku.width + extraDistance) / props.speed
  65. const trackSpacing = calculateTrackSpacing()
  66. const danmakuHeight = calculateDanmakuHeight()
  67. // 计算弹幕的垂直位置,确保在轨道中居中且不超出容器边界
  68. const trackTop = danmaku.track * trackSpacing
  69. const centerOffset = trackSpacing / 2
  70. const topPosition = Math.max(
  71. danmakuHeight / 2, // 确保不超出顶部
  72. Math.min(
  73. trackTop + centerOffset, // 轨道中心位置
  74. props.height - danmakuHeight / 2 // 确保不超出底部
  75. )
  76. )
  77. return {
  78. top: `${topPosition}px`,
  79. left: `${danmaku.left}px`,
  80. transition: `left ${duration}s linear`
  81. }
  82. }
  83. // 计算弹幕实际宽度
  84. const calculateDanmakuWidth = (text) => {
  85. // 更精确的宽度计算:每个字符约16px,头像32px,内边距40px,额外缓冲20px
  86. return text.length * 16 + 32 + 40 + 20
  87. }
  88. // 计算弹幕实际高度
  89. const calculateDanmakuHeight = () => {
  90. return 48 // 弹幕高度约48rpx
  91. }
  92. // 计算轨道间距
  93. const calculateTrackSpacing = () => {
  94. const danmakuHeight = calculateDanmakuHeight()
  95. const trackHeight = props.height / props.trackCount
  96. // 增加轨道间距,避免弹幕重叠
  97. const minSpacing = danmakuHeight + 30 // 增加间距到30px
  98. return Math.max(minSpacing, trackHeight) // 确保轨道间距足够
  99. }
  100. // 查找可用轨道
  101. const findAvailableTrack = () => {
  102. const currentTime = Date.now()
  103. // 清理过期的轨道占用记录
  104. for (let i = 0; i < trackOccupancy.value.length; i++) {
  105. if (trackOccupancy.value[i] < currentTime) {
  106. trackOccupancy.value[i] = 0
  107. }
  108. }
  109. // 简化轨道分配:使用较少的轨道数量
  110. const finalTracks = Math.min(3, props.trackCount)
  111. // 直接寻找空闲轨道
  112. for (let i = 0; i < finalTracks; i++) {
  113. if (trackOccupancy.value[i] === 0) {
  114. return i
  115. }
  116. }
  117. // 如果所有轨道都被占用,选择第一个轨道
  118. return 0
  119. }
  120. const createDanmaku = (text, avatar = null) => {
  121. const id = ++danmakuIdCounter.value
  122. const track = findAvailableTrack()
  123. const width = calculateDanmakuWidth(text)
  124. // 获取屏幕宽度,兼容不同平台
  125. const screenWidth = uni.getSystemInfoSync().screenWidth || 375
  126. const left = screenWidth + props.spacing
  127. // 简化轨道占用时间计算
  128. const duration = (screenWidth + width + 200) / props.speed
  129. const endTime = Date.now() + duration * 1000 // 移除额外缓冲时间
  130. trackOccupancy.value[track] = endTime
  131. return {
  132. id,
  133. msg: text, // 修改为msg字段,与模板保持一致
  134. icon: avatar, // 修改为icon字段,与模板保持一致
  135. track,
  136. width,
  137. left,
  138. isScrolling: false,
  139. startTime: Date.now()
  140. }
  141. }
  142. const addDanmaku = (msg, icon = null) => {
  143. console.log('添加弹幕:', { msg, icon })
  144. const danmaku = createDanmaku(msg, icon)
  145. console.log('创建的弹幕对象:', danmaku)
  146. visibleDanmakus.value.push(danmaku)
  147. console.log('当前可见弹幕数量:', visibleDanmakus.value.length)
  148. setTimeout(() => {
  149. danmaku.isScrolling = true
  150. // 确保弹幕完全离开可视范围才消失,增加更多缓冲距离
  151. danmaku.left = -(danmaku.width + 100)
  152. }, 50)
  153. // 获取屏幕宽度,兼容不同平台
  154. const screenWidth = uni.getSystemInfoSync().screenWidth || 375
  155. // 增加更多的额外距离确保弹幕完全离开可视范围
  156. const extraDistance = 200 // 增加缓冲距离
  157. const duration = (screenWidth + danmaku.width + extraDistance) / props.speed
  158. setTimeout(() => {
  159. removeDanmaku(danmaku.id)
  160. }, duration * 1000)
  161. }
  162. const removeDanmaku = (id) => {
  163. const index = visibleDanmakus.value.findIndex(item => item.id === id)
  164. if (index > -1) {
  165. visibleDanmakus.value.splice(index, 1)
  166. emit('danmakuComplete', id)
  167. }
  168. }
  169. const clearDanmakus = () => {
  170. visibleDanmakus.value = []
  171. // 清空轨道占用记录
  172. trackOccupancy.value = new Array(props.trackCount).fill(0)
  173. }
  174. const startDanmakuAnimation = () => {
  175. console.log('开始弹幕动画,数据列表:', props.danmakuList)
  176. if (props.danmakuList.length === 0) {
  177. console.log('弹幕列表为空,不启动动画')
  178. return
  179. }
  180. let currentIndex = 0
  181. const playNext = () => {
  182. if (currentIndex >= props.danmakuList.length) {
  183. if (props.infinite) {
  184. currentIndex = 0
  185. } else {
  186. return
  187. }
  188. }
  189. const danmaku = props.danmakuList[currentIndex]
  190. console.log('播放弹幕:', danmaku)
  191. // 直接播放弹幕,不检查轨道占用
  192. addDanmaku(danmaku.msg, danmaku.icon)
  193. currentIndex++
  194. // 减少弹幕播放间隔
  195. const baseInterval = Math.max(2000, props.height * 2) // 减少基础间隔
  196. const minInterval = baseInterval
  197. const maxInterval = baseInterval + 2000 // 减少随机间隔范围
  198. const interval = Math.random() * (maxInterval - minInterval) + minInterval
  199. animationTimer.value = setTimeout(playNext, interval)
  200. }
  201. playNext()
  202. }
  203. const stopDanmakuAnimation = () => {
  204. if (animationTimer.value) {
  205. clearTimeout(animationTimer.value)
  206. animationTimer.value = null
  207. }
  208. }
  209. watch(() => props.danmakuList, (newList) => {
  210. console.log('弹幕数据变化:', newList)
  211. if (newList.length > 0) {
  212. console.log('弹幕数据不为空,重新启动动画')
  213. stopDanmakuAnimation()
  214. clearDanmakus()
  215. startDanmakuAnimation()
  216. } else {
  217. console.log('弹幕数据为空')
  218. }
  219. }, { deep: true })
  220. onMounted(() => {
  221. if (props.danmakuList.length > 0) {
  222. startDanmakuAnimation()
  223. }
  224. })
  225. onUnmounted(() => {
  226. stopDanmakuAnimation()
  227. })
  228. defineExpose({
  229. addDanmaku,
  230. clearDanmakus,
  231. startDanmakuAnimation,
  232. stopDanmakuAnimation
  233. })
  234. </script>
  235. <style lang="scss" scoped>
  236. .danmaku-container {
  237. width: 100%;
  238. position: relative;
  239. overflow: hidden;
  240. // background: rgba(0, 0, 0, 0.1);
  241. border-radius: 8rpx;
  242. }
  243. .danmaku-stage {
  244. width: 100%;
  245. height: 100%;
  246. position: relative;
  247. }
  248. .danmaku-item {
  249. position: absolute;
  250. top: 0;
  251. left: 0;
  252. z-index: 10;
  253. pointer-events: none;
  254. &.danmaku-scrolling {
  255. transition: left linear;
  256. }
  257. // 确保弹幕在轨道中居中显示
  258. transform: translateY(-50%);
  259. }
  260. .danmaku-content {
  261. display: flex;
  262. align-items: center;
  263. background: rgba(0, 0, 0, 0.6);
  264. border-radius: 20rpx;
  265. padding: 8rpx 20rpx;
  266. backdrop-filter: blur(10rpx);
  267. border: 1rpx solid rgba(255, 255, 255, 0.2);
  268. // box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
  269. width: fit-content;
  270. min-width: 120rpx;
  271. // 确保弹幕内容不会超出容器边界
  272. max-height: 48rpx;
  273. overflow: hidden;
  274. // 防止弹幕在滚动过程中高度变化
  275. line-height: 1.2;
  276. // 增加内边距确保文字有足够空间
  277. box-sizing: border-box;
  278. }
  279. .danmaku-avatar {
  280. width: 32rpx;
  281. height: 32rpx;
  282. border-radius: 50%;
  283. margin-right: 12rpx;
  284. border: 2rpx solid rgba(255, 255, 255, 0.3);
  285. flex-shrink: 0;
  286. // 确保头像高度稳定
  287. object-fit: cover;
  288. }
  289. .danmaku-text {
  290. color: #000;
  291. font-size: 24rpx;
  292. font-weight: 500;
  293. // text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
  294. white-space: nowrap;
  295. overflow: hidden;
  296. text-overflow: ellipsis;
  297. max-width: 400rpx;
  298. flex: 1;
  299. // 确保文字高度稳定
  300. line-height: 1.2;
  301. height: 32rpx;
  302. display: flex;
  303. align-items: center;
  304. // 增加文字间距确保显示完整
  305. letter-spacing: 1rpx;
  306. }
  307. .danmaku-track .danmaku-content {
  308. background: rgba(244, 246, 248, 0.6);
  309. }
  310. </style>