NativeDanmuComponent.vue 14.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
<template>
  <view class="native-danmu-container">
    <!-- 弹幕显示区域 -->
    <view
      class="danmu-display-area"
      :style="{ height: containerHeight + 'rpx' }"
    >
      <!-- 弹幕轨道 -->
      <view
        v-for="(track, trackIndex) in tracks"
        :key="trackIndex"
        class="danmu-track"
        :style="{ top: trackIndex * trackHeight + 'rpx', height: trackHeight + 'rpx' }"
      >
        <!-- 轨道中的弹幕 -->
        <view
          v-for="danmu in track.danmus"
          :key="danmu.id"
          class="danmu-item"
          :style="getDanmuStyle(danmu, trackIndex)"
          @tap="handleDanmuClick(danmu)"
        >
          <!-- 弹幕内容 -->
          <view class="danmu-content">
            <!-- 头像 -->
            <view class="danmu-avatar-container">
              <image
                :src="danmu.data.avatar"
                class="danmu-avatar"
                mode="aspectFill"
              />
            </view>

            <!-- 信息区域 -->
            <view class="danmu-info">
              <!-- 标题行 -->
              <view class="danmu-title-row">
                <text class="family-name">{{ danmu.data.familyName }}</text>
              </view>

              <!-- 介绍 -->
              <text class="family-intro">{{ danmu.data.familyIntro }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import Taro from '@tarojs/taro'

// Props
const props = defineProps({
  // 弹幕容器高度
  containerHeight: {
    type: Number,
    default: 400
  },
  // 是否显示控制面板
  showControls: {
    type: Boolean,
    default: true
  },
  // 自定义弹幕数据
  customComments: {
    type: Array,
    default: () => []
  },
  // 弹幕速度 (rpx/s)
  danmuSpeed: {
    type: Number,
    default: 120  // 提高默认速度,让弹幕移动更流畅
  },
  // 轨道数量
  trackCount: {
    type: Number,
    default: 6  // 适当减少轨道数量,确保有足够间距
  }
})

// Emits
const emit = defineEmits(['danmu-click', 'danmu-hover'])

// 响应式数据
const isPlaying = ref(false)
const danmuId = ref(0)
const trackHeight = ref(110) // 适配最多3行文字显示,确保弹幕之间有足够间距
const animationTimers = ref(new Map()) // 存储动画定时器

// 轨道系统
const tracks = reactive(
  Array.from({ length: props.trackCount }, (_, index) => ({
    id: index,
    danmus: [],
    lastDanmuTime: 0
  }))
)

// Mock 数据 - 家庭弹幕内容
const baseFamilyData = {
  familyName: '幸福之家',
  familyIntro: '7口之家,父母健康,有儿有女,孩子活泼可爱,我们工作顺利',
  avatar: 'https://cdn.ipadbiz.cn/lls_prog/images/%E5%85%A8%E5%AE%B6%E7%A6%8F3_%E5%89%AF%E6%9C%AC.jpg?imageMogr2/strip/quality/60',
}

// 生成1000条相同的弹幕数据
const mockFamilyDanmus = Array.from({ length: 1000 }, (_, index) => ({
  id: (index + 1).toString(),
  ...baseFamilyData
}))

// 获取弹幕样式
const getDanmuStyle = (danmu, trackIndex) => {
  // 计算垂直位置,确保每个轨道有明确的垂直间距
  const topPosition = trackIndex * (trackHeight.value + 15) // 轨道间增加15rpx间距,适配3行文字

  return {
    transform: `translateX(${danmu.x}rpx)`,
    transition: danmu.isMoving ? `transform ${danmu.duration}ms linear` : 'none',
    opacity: danmu.opacity || 1,
    // 明确设置垂直位置
    position: 'absolute',
    left: 0,
    top: `${topPosition}rpx`,
    zIndex: 10,
    // 添加硬件加速
    willChange: 'transform'
  }
}

// 检查轨道中是否有足够空间放置新弹幕
const checkTrackSpace = (track, danmuWidth = 350) => {
  const now = Date.now()

  // 如果轨道为空,可以直接放置
  if (track.danmus.length === 0) {
    return true
  }

  // 检查最后一个弹幕的位置和时间
  const lastDanmu = track.danmus[track.danmus.length - 1]
  const timeSinceLastDanmu = now - track.lastDanmuTime

  // 更精确的位置计算
  const elapsedTime = now - lastDanmu.startTime
  const totalDistance = 750 + danmuWidth + 100 // 总移动距离
  const moveDistance = Math.min((elapsedTime / lastDanmu.duration) * totalDistance, totalDistance)
  const lastDanmuCurrentX = 750 - moveDistance

  // 调整安全间距,考虑3行文字的情况
  const minSafeDistance = danmuWidth * 0.4 // 增加到40%,为3行文字预留更多空间
  const safeDistance = danmuWidth + minSafeDistance // 弹幕宽度 + 40%弹幕长度作为间距
  const hasEnoughSpace = lastDanmuCurrentX < (750 - safeDistance)

  // 适当增加时间间隔,确保3行文字弹幕有足够的显示时间
  const minTimeInterval = 1800 // 从1600ms增加到1800ms,为3行文字预留更多时间
  const hasEnoughTime = timeSinceLastDanmu >= minTimeInterval

  // 双重检查:时间和空间都满足才允许放置
  return hasEnoughTime && hasEnoughSpace
}

// 找到可用的轨道 - 随机选择而非按顺序
const findAvailableTrack = () => {
  // 过滤出有足够空间的轨道
  const availableTracks = tracks.filter(track => checkTrackSpace(track))

  // 如果没有可用轨道,返回null
  if (availableTracks.length === 0) {
    return null
  }

  // 从可用轨道中随机选择一个
  const randomIndex = Math.floor(Math.random() * availableTracks.length)
  return availableTracks[randomIndex]
}

// 创建弹幕对象
const createDanmu = (data) => {
  const id = `danmu_${danmuId.value++}`
  const containerWidth = 750 // 小程序默认宽度
  const danmuWidth = 350 // 弹幕宽度
  const extraDistance = 100 // 额外移动距离,确保完全消失

  return {
    id,
    data,
    x: containerWidth, // 从右侧开始
    isMoving: false,
    opacity: 1,
    duration: ((containerWidth + danmuWidth + extraDistance) / (props.danmuSpeed * 0.6)) * 1000, // 减慢速度,让弹幕在屏幕上停留更久
    startTime: Date.now()
  }
}

// 添加弹幕到轨道
const addDanmuToTrack = (danmu) => {
  const track = findAvailableTrack()
  if (!track) return false

  track.danmus.push(danmu)
  track.lastDanmuTime = Date.now()

  // 启动弹幕动画
  nextTick(() => {
    startDanmuAnimation(danmu, track)
  })

  return true
}

// 启动弹幕动画
const startDanmuAnimation = (danmu, track) => {
  if (!isPlaying.value) return

  // 清除之前的定时器(如果存在)
  if (animationTimers.value.has(danmu.id)) {
    clearTimeout(animationTimers.value.get(danmu.id))
    animationTimers.value.delete(danmu.id)
  }

  // 设置动画 - 从右侧移动到左侧屏幕外
  danmu.isMoving = true

  // 使用 nextTick 确保 DOM 更新后再启动动画
  nextTick(() => {
    // 移动到左侧屏幕外,确保弹幕完全消失
    danmu.x = -(450) // 移动距离 = 弹幕宽度(350) + 额外距离(100)
  })

  // 监听动画结束事件,实现循环
  const timer = setTimeout(() => {
    // 动画结束后,重置弹幕位置到右侧,开始新的循环
    resetDanmuForLoop(danmu, track)
  }, danmu.duration)

  animationTimers.value.set(danmu.id, timer)
}

// 重置弹幕位置实现循环
const resetDanmuForLoop = (danmu, track) => {
  if (!isPlaying.value) return

  // 立即停止当前动画
  danmu.isMoving = false

  // 使用 nextTick 确保 DOM 更新
  nextTick(() => {
    // 重置弹幕位置到右侧
    danmu.x = 750 // 回到右侧起始位置

    // 短暂延迟后重新开始动画
    setTimeout(() => {
      if (isPlaying.value) {
        startDanmuAnimation(danmu, track)
      }
    }, 50) // 减少延迟时间
  })
}

// 从轨道移除弹幕
const removeDanmuFromTrack = (danmu, track) => {
  const index = track.danmus.findIndex(d => d.id === danmu.id)
  if (index > -1) {
    track.danmus.splice(index, 1)
  }
}

// 发送弹幕
const sendDanmu = (data) => {
  if (!isPlaying.value) return

  const danmu = createDanmu(data)
  addDanmuToTrack(danmu)
}

// 当前弹幕索引,用于顺序显示
let currentDanmuIndex = 0

// 发送顺序弹幕
const sendSequentialDanmu = () => {
  // 按顺序获取弹幕数据
  const danmuData = mockFamilyDanmus[currentDanmuIndex % mockFamilyDanmus.length]
  sendDanmu(danmuData)

  // 更新索引,循环使用
  currentDanmuIndex++
}

// 自动发送弹幕
let autoSendTimer = null
const startAutoSend = () => {
  if (autoSendTimer) return

  const sendNext = () => {
    if (isPlaying.value) {
      // 移除弹幕数量限制,直接发送弹幕
      sendSequentialDanmu()
    }
    // 优化发送间隔,在保持合理间距的同时增加密度
    autoSendTimer = setTimeout(sendNext, 1000 + Math.random() * 600) // 1.0-1.6秒随机间隔,适度增加发送频率
  }

  sendNext()
}

const stopAutoSend = () => {
  if (autoSendTimer) {
    clearTimeout(autoSendTimer)
    autoSendTimer = null
  }
}

// 暂停/播放弹幕
const toggleDanmu = () => {
  isPlaying.value = !isPlaying.value

  if (isPlaying.value) {
    // 恢复播放时,重新启动所有弹幕的动画
    tracks.forEach(track => {
      track.danmus.forEach(danmu => {
        if (!danmu.isMoving) {
          startDanmuAnimation(danmu, track)
        }
      })
    })
    startAutoSend()
  } else {
    // 暂停时,停止自动发送但保持弹幕在当前位置
    stopAutoSend()
  }
}

// 清空所有弹幕
const clearDanmu = () => {
  // 清除所有动画定时器
  animationTimers.value.forEach(timer => clearTimeout(timer))
  animationTimers.value.clear()

  // 清空所有轨道的弹幕
  tracks.forEach(track => {
    track.danmus = []
    track.lastDanmuTime = 0
  })
}

// 处理弹幕点击
const handleDanmuClick = (danmu) => {
  emit('danmu-click', danmu.data)

  Taro.showToast({
    title: `点击了${danmu.data.familyName}`,
    icon: 'none',
    duration: 2000
  })
}

// 暴露方法给父组件
defineExpose({
  toggleDanmu,
  clearDanmu,
  sendCustomDanmu: sendDanmu
})

// 生命周期
onMounted(() => {
  // 自动开始播放并发送初始弹幕
  isPlaying.value = true

  // 页面加载后,优化初始弹幕发送,保持合理间距和密度
  setTimeout(() => {
    for (let i = 0; i < 4; i++) { // 适度增加初始弹幕数量
      setTimeout(() => {
        sendSequentialDanmu()
      }, i * 800) // 调整发送间隔到0.8秒,平衡密度和间距
    }
  }, 400) // 减少初始延迟

  // 启动自动发送
  startAutoSend()
})

onUnmounted(() => {
  stopAutoSend()
  clearDanmu()
})
</script>

<style >
.native-danmu-container {
  width: 100%;
  position: relative;
}

.danmu-display-area {
  width: 100%;
  /* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
  /* border-radius: 20rpx; */
  position: relative;
  overflow: hidden;
  /* box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1); */
}

.danmu-track {
  position: absolute;
  width: 100%;
  left: 0;
  pointer-events: none;
}

.danmu-item {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: auto;
  z-index: 10;
  right: 0; /* 从右侧开始 */
}

.danmu-content {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.65);
  border-radius: 30rpx;
  padding: 16rpx 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
  backdrop-filter: blur(12rpx);
  border: 2rpx solid rgba(255, 255, 255, 0.4);
  max-width: 350rpx;
  min-width: 300rpx;
  margin: 8rpx 0;
  transition: all 0.3s ease;
}

.danmu-avatar-container {
  flex-shrink: 0;
  margin-right: 16rpx;
  position: relative;
}

.danmu-avatar {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  border: 3rpx solid #fff;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.danmu-avatar-container::after {
  content: '';
  position: absolute;
  top: -2rpx;
  left: -2rpx;
  right: -2rpx;
  bottom: -2rpx;
  border-radius: 50%;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4, #45b7d1, #96ceb4);
  z-index: -1;
  animation: rotate 3s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.danmu-info {
  flex: 1;
  min-width: 0;
}

.danmu-title-row {
  display: flex;
  align-items: center;
  margin-bottom: 6rpx;
}

.family-name {
  font-weight: 700;
  color: #1a202c;
  font-size: 28rpx;
  margin-right: 12rpx;
  flex-shrink: 0;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
}

.member-badge {
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
  padding: 4rpx 12rpx;
  border-radius: 16rpx;
  font-size: 20rpx;
  font-weight: 600;
  flex-shrink: 0;
  box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
}

.family-intro {
  color: #4a5568;
  font-size: 24rpx;
  display: -webkit-box;
  margin-bottom: 6rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  font-weight: 500;
}

.danmu-bottom-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.family-motto {
  color: #2d3748;
  font-size: 22rpx;
  font-style: italic;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 12rpx;
  opacity: 0.8;
}

.steps-badge {
  background: linear-gradient(45deg, #48bb78, #38a169);
  color: white;
  padding: 4rpx 12rpx;
  border-radius: 14rpx;
  font-size: 20rpx;
  font-weight: 600;
  flex-shrink: 0;
  box-shadow: 0 2rpx 8rpx rgba(72, 187, 120, 0.3);
}

.danmu-controls {
  display: flex;
  justify-content: center;
  gap: 20rpx;
  margin-top: 20rpx;
  padding: 0 20rpx;
}

.control-btn {
  flex: 1;
  max-width: 200rpx;
  height: 60rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
}

/* 弹幕动画效果 */
.danmu-moving {
  transition-timing-function: linear;
  transition-property: transform;
}

/* 弹幕项基础样式 */
.danmu-item {
  position: absolute;
  z-index: 10;
  will-change: transform;
  backface-visibility: hidden;
  transform-style: preserve-3d;
  left: 0;
  top: 0;
  width: auto;
  height: auto;
}

/* 悬停效果 */
.danmu-item:active .danmu-content {
  transform: scale(0.98);
  box-shadow: 0 12rpx 32rpx rgba(0, 0, 0, 0.18);
  transition: all 0.2s ease;
}

.danmu-content:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 12rpx 32rpx rgba(0, 0, 0, 0.16);
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .danmu-content {
    max-width: 300rpx;
    min-width: 240rpx;
    padding: 10rpx 16rpx;
  }

  .danmu-avatar {
    width: 40rpx;
    height: 40rpx;
    margin-right: 12rpx;
  }

  .family-name {
    font-size: 24rpx;
  }

  .family-intro {
    font-size: 20rpx;
  }
}
</style>