danmakuManager.vue 9.7 KB

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