bytedance / danmu.js

HTML5 danmu (danmaku) plugin for any DOM element
MIT License
290 stars 34 forks source link
barrage bullet-screen danmaku danmu html5 live-commenting

概述

运用 danmu.js 可以方便地使用弹幕功能,满足任意 Web DOM 元素使用(包括 video)。弹幕实现了顶部居中、底部居中、彩色弹幕、无遮挡滚动(具体算法参考前端算法之弹幕设计),以及其它常用的弹幕使用方式。

起步

  1. 安装

    $ npm install danmu.js
  2. 使用

这是 danmu.js 的 npm 使用方法,cdn 使用可以参考示例。DEMO

Properties

danmu.status // 主进程运行状态 'idle' | 'paused' | 'playing' | 'closed'
danmu.state : {
    status: danmu.status,
    comments: Array<CommentData>, // 弹幕数据池
    bullets: Array<Bullet>, // 在轨弹幕数据
    displayArea: { width: number, height: number } // 弹幕显示区域状态
}

API

danmu.start() //弹幕初始化并播放(内部默认已调用)
danmu.pause() //弹幕暂停
danmu.play() //弹幕继续播放
danmu.stop() //弹幕停止并消失

// 单条更新弹幕数据,适合在用户发送弹幕时调用
danmu.sendComment({
  //发送弹幕
  duration: 15000,
  id: 'id',
  start: 3000, //不提供该项则立即发送
  txt: '弹幕内容',
  style: {
    color: '#ff9500',
    fontSize: '20px',
    border: 'solid 1px #ff9500',
    borderRadius: '50px',
    padding: '5px 11px',
    backgroundColor: 'rgba(255, 255, 255, 0.1)'
  }
})

// 批量更新弹幕数据,适合在从接口中获取到批量数据时调用
danmu.updateComments([
  {
    duration: 15000,
    id: 'id',
    start: 3000, //不提供该项则立即发送
    txt: '弹幕内容',
    style: {
      color: '#ff9500',
      fontSize: '20px',
      border: 'solid 1px #ff9500',
      borderRadius: '50px',
      padding: '5px 11px',
      backgroundColor: 'rgba(255, 255, 255, 0.1)'
    }
  },
  ...
])

danmu.setCommentDuration(id, duration) //按照id改变某一个弹幕的持续显示时间
danmu.setAllDuration(mode, duration) // 改变所有弹幕的持续显示时间,包括已加入队列弹幕
danmu.setPlayRate(mode, 1) // 设置弹幕播放速率,在弹幕播放速度上乘以一个系数,控制速度的变化。支持有不同显示时长弹幕的需求
danmu.setCommentID(oldID, newID) //改变某一个弹幕的id
danmu.hide(mode) //屏蔽某一类弹幕(参数可选值 scroll | top | bottom | color)
danmu.show(mode) //显示某一类弹幕(参数可选值 scroll | top | bottom | color)
danmu.setArea(area) // 修改弹幕显示区域, 参考上方config中area的配置
danmu.setOpacity(opacity) // 设置透明度
danmu.setFontSize(size, channelSize) // 设置样式 size 为字体大小 channelSize 如果不需要修改轨道大小则无需传入 channelSize
danmu.setCommentLike(id, {
  el: likeDOM,
  style: {
    paddingLeft: '10px',
    color: '#ff0000'
  }
}) // 这是点赞样式,id 为 commentid

Dev

我们为开发者提供了示例,使用方式如下:

$ git clone git@github.com:bytedance/danmu.js.git
$ cd danmu.js
$ yarn
$ yarn build
$ yarn serve

访问 http://localhost:3000/demo/index.html

License

MIT