danmakuManager.vue 9.3 KB

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