### Install via Package Managers
Source: https://jabbany.github.io/CommentCoreLibrary
Commands for installing the library using Bower or npm.
```bash
bower install comment-core-library
```
```bash
npm install comment-core-library
```
--------------------------------
### Install via Rails Gemfile
Source: https://jabbany.github.io/CommentCoreLibrary
Configuration for adding the library to a Ruby on Rails project using rails-assets.
```ruby
# Add https://rails-assets.org as the new gem source
source 'https://rails-assets.org'
gem 'rails-assets-comment-core-library'
```
--------------------------------
### Acfun Danmaku Format Examples
Source: https://jabbany.github.io/CommentCoreLibrary/docs/data-formats/acfun-json.html
JSON structure examples for v1 and v2 danmaku formats.
```json
{
"c": ...,
"m": ... or JSON.stringify({
"l": ...,
"p": ...,
"pz": ...,
"rx": ...,
"k": ...,
"r": ...,
"e": ...,
"f": ...,
"sz": ...,
"c": ...,
"z": [ ... ]
}),
}
```
```json
{
"mode": ...,
"color": ...,
"size": ...,
"user": ...,
"stime": ...,
"time": ...,
"message": ... or JSON.stringify({
"l": ...,
"p": ...,
"pz": ...,
"rx": ...,
"k": ...,
"r": ...,
"e": ...,
"f": ...,
"sz": ...,
"c": ...,
"z": [ ... ]
})
}
```
--------------------------------
### Bilibili XML Danmaku Format Example
Source: https://jabbany.github.io/CommentCoreLibrary/docs/data-formats/bilibili-xml.html
The basic XML structure for Bilibili danmaku files.
```xml
chat.bilibili.tv91236k-v...
```
--------------------------------
### Standard Code Bullet Comment
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentTypes.html
Executes code at the start of the bullet comment within a restricted runtime space.
```text
可选参量:代码 定义一条代码弹幕。代码会在弹幕开始时被执行,并且被局限于一个弹幕的运行时空间。 有关代码弹幕请参考 [scripting](scripting/readme.md) 章节。CCL的代码弹幕实现与 Bilibili 原版高级弹幕的API有兼容层(新版采用BAS语法),这表示一些 Bilibili 的高级弹幕可以无须更改的 运行在 CCL代码弹幕引擎上。另一些代码弹幕则需少量的更改(或者视情况可能需要一些结构重构)。
```
--------------------------------
### init(rendererType)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentManager.html
Initializes the manager and sets the rendering engine type.
```APIDOC
## init(rendererType:string)
### Description
Initializes the manager and binds the stage size. Ensure the stage is accessible and has measurable dimensions before calling.
### Parameters
#### Query Parameters
- **rendererType** (string) - Optional - The rendering engine to use: 'css' (default), 'svg', 'canvas', or 'legacy'.
```
--------------------------------
### Configure Timeline Modes for Live Comments
Source: https://jabbany.github.io/CommentCoreLibrary/docs/DoingItRight.html
Demonstrates initialization for non-timeline (live screen) and timeline-based (video streaming) comment modes.
```javascript
CM = new CommentManager(...);
CM.init();
CM.start();
// 注意我们在这种模式下无需调用time或者伪造时间轴
// 某种方式获得了新的弹幕后...(此处示例socket模式)
socket.on('danmaku', function (data) {
CM.send(commentData); // 注意这里直接用了 CM.send 全程也无需调用 time
});
```
```javascript
CM = new CommentManager(...);
CM.init();
CM.start();
videoStream.addEventListener('timeUpdate', function () {
CM.time(videoStream.currentTime * 1000); // 时刻通知流媒体播放时间
});
socket.on('danmaku-update', function (data) {
CM.insert(data); // 注意这里是把弹幕插入时间轴。
});
```
--------------------------------
### Demonstrate Object Cloning Synchronization Issues
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/Display
Illustrates how cloning Transform objects leads to synchronization conflicts between the internal state and the external sandbox instance.
```javascript
var a = clone((new CommentField("f1")).transform);
var b = clone(a);
var m1 = new Matrix();
var m2 = new Matrix();
// a,b 为不同对象实例,但是绑定了同一个 CommentField
a.matrix = m1;
// 此时 CommentField 的变换Matrix是 m1, a.matrix == m1,b.matrix != m1
b.matrix = m2;
// 此时 CommentField 的变换Matrix是 m2, a.matrix == m1,b.matrix == m2
// a.matrix !== b.matrix
// 此时 b 是 CommentField 的真实 transform,而再次读取 CommentField 的
// transform属性將返回错误的transform信息
```
--------------------------------
### ライブラリのインストールコマンド
Source: https://jabbany.github.io/CommentCoreLibrary/docs/Tutorial.ja_JP.html
npmを使用したライブラリの取得および開発環境のセットアップコマンド。
```bash
npm install comment-core-library --save
```
```bash
git clone https://github.com/jabbany/CommentCoreLibrary.git
```
```bash
npm install grunt-cli -g
npm install
```
--------------------------------
### Configure Multiple Redundant Parsers
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProvider.html
Adds multiple static sources with different formats and their respective parsers to the provider.
```javascript
var provider = new CommentProvider();
provider.addStaticSource(CommentProvider.XMLProvider('GET', 'http://localhost/danmaku.xml'), CommentProvider.SOURCE_XML);
provider.addStaticSource(CommentProvider.TextProvider('GET', 'http://localhost/backup-danmaku.txt'), CommentProvider.SOURCE_TEXT);
provider.addParser(new BilibiliFormat.XMLParser(), CommentProvider.SOURCE_XML);
provider.addParser(new BilibiliFormat.TextParser(), CommentProvider.SOURCE_TEXT);
```
--------------------------------
### Configure Static XML Comment Provider
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProvider.html
Sets up a CommentProvider with a static XML source, a corresponding parser, and a target CommentManager.
```javascript
// 制作弹幕供应器
var provider = new CommentProvider();
// 添加一个静态弹幕源(只加载一次)
provider.addStaticSource(CommentProvider.XMLProvider('GET', 'http://localhost/danmaku.xml'), CommentProvider.SOURCE_XML)
// 添加一个解析器
provider.addParser(new BilibiliFormat.XMLParser(), CommentProvider.SOURCE_XML);
// 添加一个目标 (CommentManager)
var cm = new CommentManager($('my-comment-container'));
provider.addTarget(cm);
// 加载弹幕并启动 cm
cm.init();
provider.load().then(function () {
cm.start();
}).catch(function (e) {
alert('载入弹幕出错了!' + e);
});
```
--------------------------------
### interval(callback:Function, interval:number, repeat:number):number/Runtime.Timer
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/Utils
Sets up a recurring timer.
```APIDOC
## interval(callback:Function, interval:number = 1000, repeat:number = 1):number/Runtime.Timer
### Description
Executes a callback function at a specified interval for a set number of repetitions. If repeat is 0, it runs indefinitely.
### Parameters
- **callback** (Function) - Required - The function to execute.
- **interval** (number) - Optional - Interval in milliseconds (default: 1000).
- **repeat** (number) - Optional - Number of repetitions (default: 1).
### Returns
- (number|Runtime.Timer) - Returns an identifier or a Runtime.Timer instance.
```
--------------------------------
### Implement EventDispatcher Dynamic Source
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProvider.html
Demonstrates handling dynamic comments via an EventDispatcher listener.
```javascript
var source = new EventDispatcher();
source.addEventListener('receive', e => {
cm.send(Parser.parseOne(e));
});
```
--------------------------------
### Configure Real-time Dynamic Comments
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProvider.html
Binds a dynamic source and a parser to the provider for real-time comment processing.
```javascript
var provider = new CommentProvider();
// 绑定动态源,动态源可以是两种:LongPoll 或者 EventDispatcher
provider.addDynamicSource(source, CommentProvider.SOURCE_JSON);
// 会使用 parseOne 来逐个解析动态弹幕
provider.addParser(new SomeFormat.JSONParser(), CommentProvider.SOURCE_JSON);
provider.addTarget(cm);
```
--------------------------------
### Static Provider Methods
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProvider.html
Built-in static methods for creating data providers.
```APIDOC
## BaseHttpProvider(method: String, url: String, responseType: String, args: Object, body: *): Promise
### Description
Performs an XHR request to fetch data.
## JSONProvider(method: String, url: String, args: String, body: *): Promise
### Description
Resolves to a JSON result.
## XMLProvider(method: String, url: String, args: String, body: *): Promise
### Description
Resolves to a document object (DOM/XML).
## TextProvider(method: String, url: String, args: String, body: *): Promise
### Description
Resolves to a string.
```
--------------------------------
### Configure Multi-format Automatic Fallback
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProvider.html
Registers multiple parsers for the same source type to handle different formats.
```javascript
var provider = new CommentProvider();
provider.addStaticSource(CommentProvider.XMLProvider('GET', 'http://localhost/danmaku.xml'), CommentProvider.SOURCE_XML);
provider.addParser(new SomeFormat.XMLParser(), CommentProvider.SOURCE_XML);
provider.addParser(new SomeOtherFormat.XMLParser(), CommentProvider.SOURCE_XML);
```
--------------------------------
### Implement LongPoll Dynamic Source
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProvider.html
Demonstrates a manual polling loop for dynamic comment sources using LongPoll.
```javascript
var source = new LongPollDynamicSource();
var poller = source.get();
while(true) {
poller = poller.then(obj => {
cm.send(Parser.parseOne(obj));
return source.get();
})
}
```
--------------------------------
### __trace(object:Object, traceMode:String)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/OOAPI.html
Low-level trace function for logging messages with different severity levels.
```APIDOC
## __trace(object:Object, traceMode:String)
### Description
Logs messages to the system. The traceMode determines the severity: 'log', 'warn', 'err', or 'fatal'.
### Parameters
- **object** (Object) - The message or object to trace.
- **traceMode** (String) - The mode of the trace ('log', 'warn', 'err', 'fatal').
```
--------------------------------
### HTMLへのライブラリ読み込み
Source: https://jabbany.github.io/CommentCoreLibrary/docs/Tutorial.ja_JP.html
HTMLのheadタグ内でCSSとJSファイルを読み込む設定。
```html
... 其他头部信息 ...
... 其他头部信息 ...
```
--------------------------------
### Change Global Display Mode via CSS
Source: https://jabbany.github.io/CommentCoreLibrary/docs/DoingItRight.html
Modify the global CSS class for future comments by updating options.global.className.
```css
.cmt { /** 默认,描边,无粗体 **/ }
.cmt.bold { font-weight: bold; }
.cmt.shadow { /** 某些魔法的实现影子的CSS **/ }
```
--------------------------------
### Implement Push Notify for Real-time Comments
Source: https://jabbany.github.io/CommentCoreLibrary/docs/DoingItRight.html
Uses socket.io to listen for incoming comment events and JQuery to handle user input for sending new comments.
```javascript
// Push notify example code
// 基于 socket.io 和 JQuery来简化代码
var socket = io(); //开启流
socket.on('danmaku', function(data){
// 当遇到 danmaku 事件,就把推送来的弹幕推送给 CCL
var danmaku = yourFormatParser(data);
if (danmaku.hasOwnProperty('stime')) {
// 弹幕有时间轴位置,那就插入时间轴
CM.insert(danmaku);
} else {
// 弹幕没有时间轴位置就立刻显示(不记录)
CM.send(danmaku);
}
});
$('#send-danmaku-btn').click(function(){
//当按了发送弹幕的按钮
var data = {
"text": $('#send-danmaku-field').value,
"stime": myVideo.currentTime,
...
};// 通过UI获取新弹幕的信息
//包装并发射弹幕
socket.emit('danmaku', JSON.stringify(yourFormatPackager(data)));
//清除 UI 文字部分
$('#send-danmaku-field').value("");
});
```
--------------------------------
### formatTimes(time:number):string
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/Utils
Formats seconds into a 'minutes:seconds' string.
```APIDOC
## formatTimes(time:number):string
### Description
Converts a duration in seconds into a string formatted as 'minutes:seconds'. Note that this does not include hours; large values will result in minute counts greater than 59.
### Parameters
- **time** (number) - Required - The duration in seconds.
### Returns
- (string) - The formatted time string.
```
--------------------------------
### constructor(clocksource: Function)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/Runtime/Runtime.TimeKeeper.ref.html
Initializes a new instance of the TimeKeeper class with an optional custom clock source function.
```APIDOC
## constructor(clocksource: Function)
### Description
Constructs an instance of `TimeKeeper` using the provided `clocksource` function to supply absolute time. If no function is provided, it defaults to `Date.now` (UNIX timestamp in milliseconds).
### Parameters
- **clocksource** (Function) - Optional - A function that returns the current absolute time in milliseconds. Defaults to `Date.now`.
```
--------------------------------
### 弾幕表示用HTML構造
Source: https://jabbany.github.io/CommentCoreLibrary/docs/Tutorial.ja_JP.html
弾幕を表示するためのコンテナ要素。
```html
```
--------------------------------
### CommentManager Methods
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentCoreLibraryAPI.html
Methods for managing the timeline, playback state, and individual comment display.
```APIDOC
## load(timeline)
Loads an array of unsorted comment data, sorts it, and overwrites the current timeline.
## start()
Starts the internal clock to begin scrolling comments.
## stop()
Pauses the internal clock and stops all currently scrolling comments and effects.
## insert(comment)
Inserts a new comment into the timeline while maintaining sorted order.
## send(comment)
Displays a comment on the stage immediately without adding it to the timeline.
## clear()
Removes all currently running comments from the stage while keeping the timeline intact.
## time(time)
Sets the playhead time of the manager in milliseconds.
```
--------------------------------
### __schannel(id:String, callback:Function)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/OOAPI.html
Subscribe to a data stream.
```APIDOC
## __schannel(id:String, callback:Function)
### Description
Subscribes to a data stream identified by the provided ID.
### Parameters
- **id** (String) - The channel identifier to subscribe to.
- **callback** (Function) - The function to execute when data is received.
```
--------------------------------
### Initialize CommentManager
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentCoreLibraryAPI.html
Initialize the CommentManager by passing the HTML DOM element that serves as the comment stage.
```javascript
var cm = new CommentManager ( HtmlDomElement stage )
```
--------------------------------
### __pchannel(id:String, payload:Object)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/OOAPI.html
Publish data to a data stream.
```APIDOC
## __pchannel(id:String, payload:Object)
### Description
Publishes data to a specific data stream.
### Parameters
- **id** (String) - The channel identifier.
- **payload** (Object) - The data to publish.
```
--------------------------------
### __channel(id:String, payload:Object, callback:Function)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/OOAPI.html
Low-level bidirectional communication interface.
```APIDOC
## __channel(id:String, payload:Object, callback:Function)
### Description
Sends a payload to a specific channel ID. If a callback is defined for the channel, it will be executed with the response.
### Parameters
- **id** (String) - The channel identifier.
- **payload** (Object) - The data to send.
- **callback** (Function) - Optional callback function for the response.
```
--------------------------------
### Positioned Bullet Comment Simple Mode
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentTypes.html
Allows precise positioning and opacity gradients using an array of parameters.
```text
可选参量:Array[x,y,opacity,duration,text] 定位弹幕简单模式允许用户对弹幕进行精确定位和透明度渐变,但是本身不包含任何3D排版效果。 opacity为形如:`[Float]-[Float]`,分别定义了始末透明度。x,y都小于 1 的时候我们认为是 百分比。
```
--------------------------------
### Include License Attribution
Source: https://jabbany.github.io/CommentCoreLibrary
Required attribution line when using the library in a project.
```text
CommentCoreLibrary (//github.com/jabbany/CommentCoreLibrary) - Licensed under the MIT license
```
--------------------------------
### CommentManager Constructor
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentCoreLibraryAPI.html
Initializes a new CommentManager instance by providing the HTML DOM element to serve as the comment stage.
```APIDOC
## new CommentManager(stage)
### Description
Initializes the CommentManager with a specific HTML DOM element. The element should have the class 'container' and be a descendant of an element with the class 'abp'.
### Parameters
- **stage** (HtmlDomElement) - Required - The DOM element to be used as the comment stage.
```
--------------------------------
### load(timeline)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentManager.html
Loads an array of comment data into the timeline.
```APIDOC
## load(timeline:Array)
### Description
Loads a set of comment objects into the timeline. The manager automatically sorts them by stime. Note: This clears the previous timeline.
### Parameters
#### Request Body
- **timeline** (Array) - Required - An array of comment data objects.
```
--------------------------------
### CommentProvider Methods
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProvider.html
Methods available on the CommentProvider instance for managing sources, parsers, and targets.
```APIDOC
## addStaticSource(provider: Promise, type: String): this
### Description
Adds a static provider and binds it to provide the specified data type.
### Parameters
- **provider** (Promise) - Required - The static provider instance.
- **type** (String) - Required - The data format type (e.g., CommentProvider.SOURCE_XML).
## addDynamicSource(source: DynamicSource, type: String): this
### Description
Adds and binds a dynamic provider.
### Parameters
- **source** (DynamicSource) - Required - The dynamic source instance.
- **type** (String) - Required - The data format type.
## addTarget(commentManager: CommentManager): this
### Description
Adds a target CommentManager to broadcast comment load data to.
### Parameters
- **commentManager** (CommentManager) - Required - The comment manager instance.
## addParser(parser: IParser, type: String): this
### Description
Adds a parser and binds it to a specific data format type.
### Parameters
- **parser** (IParser) - Required - The parser instance.
- **type** (String) - Required - The data format type.
## load(): Promise
### Description
(Re)loads the static sources.
## start(): Promise
### Description
Loads and binds all sources, parsers, and targets.
## destroy(): Promise
### Description
Unbinds all dynamic sources and destroys the current provider.
```
--------------------------------
### ローカル開発環境のテストURL
Source: https://jabbany.github.io/CommentCoreLibrary/docs/Tutorial.ja_JP.html
ローカルサーバーの接続確認に使用するURL。
```text
http://localhost/
```
--------------------------------
### send(data)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentManager.html
Injects a comment directly into the running list.
```APIDOC
## send(data:ICommentData)
### Description
Converts an abstract comment data object into an IComment instance and adds it to the running list. This is ideal for real-time comments that do not rely on the timeline.
### Parameters
#### Request Body
- **data** (ICommentData) - Required - The comment data object to be rendered.
```
--------------------------------
### Event Reference
Source: https://jabbany.github.io/CommentCoreLibrary/docs/Events.html
List of standard events dispatched by the CommentManager.
```APIDOC
## Event Reference
- **load**: Dispatched after successfully loading the comment timeline.
- **clear**: Dispatched after successfully clearing comments from the screen.
- **resize**: Dispatched after calling setBounds.
- **enterComment**: Dispatched when a comment enters the active list. Data parameter: Comment object.
- **exitComment**: Dispatched before a comment is removed. Data parameter: Comment object.
```
--------------------------------
### Comment Types Overview
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentTypes.html
List of supported comment modes and their corresponding type identifiers.
```APIDOC
## Comment Types
- 1: Top-anchored scrolling
- 2: Bottom-anchored scrolling
- 4: Bottom-anchored static
- 5: Top-anchored static
- 6: Top-anchored reverse
- 7: Animated positioned
- 8: Code comments
- 9: Reserved: Zoome-type
- 17: Reserved: Image
- 18: Reserved: Canvas or SVG
- 19: Reserved: Draw-command
- 20: Reserved: Motion spec
- 21: Subtitles
```
--------------------------------
### __achannel(id:String, auth:String, payload:Object)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/OOAPI.html
Authenticated one-way communication interface.
```APIDOC
## __achannel(id:String, auth:String, payload:Object)
### Description
Sends authenticated data to a specific channel ID.
### Parameters
- **id** (String) - The channel identifier.
- **auth** (String) - The authentication string.
- **payload** (Object) - The data to send.
```
--------------------------------
### Autoscale Comment Container
Source: https://jabbany.github.io/CommentCoreLibrary/docs/DoingItRight.html
Scale the comment stage container to maintain visual consistency when the player size changes. Ensure the resize event is bound to all relevant container triggers.
```javascript
// cm.stage 的父对象或播放器容器等会变大的东西
var containerParent = document.getElementById("container-parent");
// 记住默认大小,此处亦可换成固定的默认大小
var defWidth = CM.width, defHeight = CM.height;
// 这里代表任何播放器/父对象的的resize,如果有多处可能触发resize的地方(如全屏化)都须绑定
containerParent.addEventListener('resize', function () {
var stage = CM.stage; // CommentManager 的 stage
// 计算缩放比例,只看宽度
var scale = containerParent.offsetWidth / defWidth;
var relHeight = containerParent.offsetHeight / scale;
// 把弹幕舞台设置成小版舞台
CM.setBounds(defWidth, relHeight);
stage.style.width = defWidth;
stage.style.height = relHeight;
// 用 CSS 来拉伸
stage.style.transform = "scale(" + scale + ")";
});
```
--------------------------------
### Coordinates Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the x and y properties for positioning.
```text
类型限制:mode > 6 弹幕坐标位置(起始),这个属性只在定位弹幕或更高级的弹幕中才被利用。动态弹幕将会以此值为初始移动 位置,而静态弹幕则会在标出的位置生成。有些高级弹幕虽然也有x,y属性。虽然一般情况下x,y属性都表示 位置坐标,但是有些高级弹幕中这个属性起到的效果未必是定位,具体需要参考该类型实现。
```
--------------------------------
### Opacity Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the opacity property for comment transparency.
```text
类型限制:无 不透明度。取值 [0,1], `0`为完全透明,`1`为完全不透明。默认 `1`。
```
--------------------------------
### Alignment Anchor Configuration
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentObject.html
Table defining the alignment anchor points based on the align property value.
```text
Byte | Number | Alignment
------------------------------------------
0 0 | 0 | Top Left (Default)
------------------------------------------
0 1 | 1 | Top Right
------------------------------------------
1 0 | 2 | Bottom Left
------------------------------------------
1 1 | 3 | Bottom Right
------------------------------------------
1 0 0 | 4 | Top Center
------------------------------------------
1 0 1 | 5 | Center Right
------------------------------------------
1 1 0 | 6 | Bottom Center
------------------------------------------
1 1 1 | 7 | Center Left
------------------------------------------
1 0 0 0 | 8 | Center Center
```
--------------------------------
### Font Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the font property for rendering.
```text
类型限制:无 设定弹幕渲染字体(如果为空,则使用默认字体)。
```
--------------------------------
### addEventListener(event, listener)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/Events.html
Registers a listener function for a specific event type.
```APIDOC
## addEventListener(event, listener)
### Description
Binds a listener function to a specific event triggered by the CommentManager.
### Parameters
- **event** (string) - The name of the event to listen for.
- **listener** (function) - The callback function to execute when the event is dispatched.
```
--------------------------------
### Positioning Mode Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the position property for coordinate systems.
```text
类型限制:mode > 6 弹幕坐标是相对还是绝对坐标。取值 `absolute` 时 x,y 表示对象锚点距离舞台原点的横纵像素绝对 坐标。当取值 `relative` 时 x,y 表示锚点距离原点的距离相对于舞台宽高的比例。例 `x=0.5,y=0.5` 时,锚点在舞台正中央。
```
--------------------------------
### timer(callback:Function, delay:number):number
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/Utils
Executes a callback after a specified delay.
```APIDOC
## timer(callback:Function, delay:number = 1000):number
### Description
Calls the provided callback function after the specified delay in milliseconds.
### Parameters
- **callback** (Function) - Required - The function to execute.
- **delay** (number) - Optional - Delay in milliseconds (default: 1000).
### Returns
- (number) - Timer identifier.
```
--------------------------------
### Positioned Moving Bullet Comment Mode
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentTypes.html
Allows linear movement from an initial position to a target position with configurable duration and delay.
```text
可选参量:Array[x,y,opacity,duration,text,rotateZ,rotateY,toX,toY,(dur),(delay),(shadow),(font),(linear)] 定位移动弹幕允许用户指定了扩展弹幕后进行移动,由初始位置(x,y)线性移动到(toX,toY),同时 `dur` 表示整个移动的时长(默认`500ms`),`delay` 表示移动的滞后时间(默认为 `0ms`)。 定位移动开始于弹幕生命周期的`delay`,并完结于生命周期的 (delay+dur) 时间。 如果 `(delay+dur) > duration`,则移动会在duration到达时终止(注意此时可能并未到达移动终点) 定位弹幕的Shadow为`"true"`或`"false"`字符串,若为`false`则文字不钩边。`font`如果指定, 则会改变当前弹幕的字体。`linear`目前暂时不起作用。
```
--------------------------------
### Basic Easing Function Structure
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/Tween
The fundamental formula used to calculate the property value at a specific point in time during an animation.
```text
param = fn(time / duration) * change + begin
```
--------------------------------
### Standard Image Positioned Bullet Comment
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentTypes.html
Allows dynamic loading of image bullet comments with specified coordinates and opacity gradients.
```text
可选参量:Array[x,y,opacity,duration,url] 图片定位弹幕允许用户进行图片弹幕的动态载入,其中(x,y)为显示坐标,`opacity` 为形如 `[Float]-[Float]` 的渐变区段,而 `duration` 为生命周期。
```
--------------------------------
### dispatchEvent(event, data)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/Events.html
Dispatches an event with optional data to all registered listeners.
```APIDOC
## dispatchEvent(event, data)
### Description
Manually dispatches an event to trigger associated listeners.
### Parameters
- **event** (string) - The name of the event to dispatch.
- **data** (any) - Optional data payload to pass to the listeners.
```
--------------------------------
### Date Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the date property for timestamping.
```text
类型限制:无 发送日期,记录为时间戳。起不到渲染的作用,也对其没有影响。唯一的影响在于在排序时,两个相同 `stime`的弹幕,`date`更新的则会排在后面(渲染更靠上层)。
```
--------------------------------
### getTimer():number
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/Utils
Returns the elapsed time since the library worker thread loaded.
```APIDOC
## getTimer():number
### Description
Returns the total elapsed time in milliseconds since the library's worker thread was initialized.
### Returns
- (number) - Elapsed time in milliseconds.
```
--------------------------------
### Movable Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the movable property for positioning.
```text
类型限制:mode > 6 弹幕可移动,布尔。这个属性只在定位弹幕下有效,用于指定弹幕是否可移动。高级弹幕中的此参数不保证 作用。
```
--------------------------------
### Comment Stage HTML Structure
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentCoreLibraryAPI.html
The required HTML structure for the comment stage, where the container div acts as the target for the CommentManager.
```html
```
--------------------------------
### Axis Direction Configuration
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentObject.html
Table defining the axis growth direction based on the axis property value.
```text
Byte | Number | Axis
--------------------------------------------
0 0 | 0 | x -> right, y -> down
--------------------------------------------
0 1 | 1 | x -> left, y -> down
--------------------------------------------
1 0 | 2 | x -> right, y -> up
--------------------------------------------
1 1 | 3 | x -> left, y -> up
```
--------------------------------
### Hash Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the hash property for author identification.
```text
类型限制:无 发送弹幕者的唯一识别哈希。用于按作者过滤。存储为字符串, 而且建议最好只包含`a-zA-Z0-9-_=/.` 这些符号。
```
--------------------------------
### rgb(r:number, g:number, b:number):number
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/Utils
Converts RGB values into a single integrated RGB number.
```APIDOC
## rgb(r:number, g:number, b:number):number
### Description
Converts individual red, green, and blue components into a single integer representation of the color.
### Parameters
- **r** (number) - Required - Red component value.
- **g** (number) - Required - Green component value.
- **b** (number) - Required - Blue component value.
### Returns
- (number) - The integrated RGB color value.
```
--------------------------------
### time(currentTime)
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentManager.html
Updates the current timeline position of the manager.
```APIDOC
## time(currentTime:Number)
### Description
Reports the current timeline time in milliseconds. The manager automatically handles time progression and rewinds, updating the active comment list accordingly.
### Parameters
#### Query Parameters
- **currentTime** (Number) - Required - The absolute time in milliseconds corresponding to the comment stime.
```
--------------------------------
### Implement Polling for Real-time Comments
Source: https://jabbany.github.io/CommentCoreLibrary/docs/DoingItRight.html
Uses setInterval to periodically fetch new comments from a server via XMLHttpRequest. Includes a flag to prevent overlapping requests if the server response is delayed.
```javascript
// Polling example code
var hasLastCheckReturned = true; // 标记之前检测是否已经完成,避免服务器过载
var lastCheckedTime = 0; // 上次检测时间
setInterval(function() {
if (!hasLastCheckReturned) {
return; // 上次还没返回结果。放弃这次请求。
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.responseCode === 200) {
// 解析新增的弹幕
var danmakuList = yourFormatParser(xhr.responseText);
for (var i = 0; i < danmakuList.length; i++) {
CM.insert(danmakuList[i]); // 把增量弹幕每一个都插入
}
lastCheckedTime = Date.now(); // 更新上次检测的时间
hasLastCheckReturned = true;
} else {
// 可能出了问题
console.log(xhr.responseText);
hasLastCheckReturned = true;
}
}
};
// 告诉服务器上次检查的时间,来获取增量
xhr.open('GET', 'http://yoururl/somevideoid/?from=' + lastCheckedTime,
true);
xhr.send(); // 发送请求
hasLastCheckReturned = false;
}, 3000); // 每3s检查新的弹幕
```
--------------------------------
### Extended Image Bullet Comment
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentTypes.html
Provides flexible image scaling and 3D rotation parameters.
```text
可选参量:Array[x,y,opacity,duration,url,rotX,rotY,rotZ,(originTL),(imgScale)] 图片弹幕的扩展格式比文字弹幕要更加灵活。imgScale定义了图片缩放比例`[Width]x[Height]`, 默认为原始大小。为"0x0"时也等同于默认大小。`rotX`,`rotY`,`rotZ`则分别定义了图片在X,Y,Z 轴向的转动量。 `originTL`是一个形如`[originT%]-[originL%]`的字符串,其定义了一下旋转中心 距离左上角的位置,默认是 `0% 0%` 处(等同于参数 `0-0`),旋转中心为整个图形的中心时,可用 `50-50`参数。右下角则是`100-100`
```
--------------------------------
### Alignment Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the align property for anchor points.
```text
类型限制:无 设定弹幕的对齐角(参考 [CommentObject](/CommentCoreLibrary/docs/CommentObject.html))。如果为空则默认取`0`。
```
--------------------------------
### Shadow Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the shadow property for text outlining.
```text
类型限制:无 设定弹幕的钩边,如果是 `false` 则禁用弹幕钩边。
```
--------------------------------
### Alpha Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the alpha property for transparency gradients.
```text
类型限制:mode > 6 or mode == 4 or mode == 5 透明度渐变,取值为 2 元素数组 `[alphaFrom, alphaTo]`。`alphaFrom`为初始透明度, `alphaTo`为终止透明度。注意:本设置在顶部和底部渐隐弹幕中也可用。
```
--------------------------------
### Top-anchored Bullet Comment
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentTypes.html
Allows specified text content, unaffected by global interface transparency.
```text
可选参量:文字 顶部弹幕允许指定内容文字。不受界面全局的透明度影响。
```
--------------------------------
### Border Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the border property for a comment object.
```text
类型限制:无 弹幕的边框,类型为布尔值,默认为`false`,最好携带此参数,发送新弹幕的弹幕,默认此值为`true`。 为`true`时,生成的弹幕对象外围将被蓝色的边框框住。
```
--------------------------------
### Motion Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the motion property for animation sequences.
```text
类型限制:mode > 6 弹幕运行轨迹,由一系列 motion 对象组成的数组。每一个motion对象参考下方定义
```
--------------------------------
### Basic ICommentData POJO Structure
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
The fundamental structure of a bullet comment object represented as a Plain Old JavaScript Object.
```json
{
"text": "...",
"mode": 1,
"stime": 10,
"size": 25,
"color": 0xffffff,
...
}
```
--------------------------------
### Add Border for Self-Sent Comments
Source: https://jabbany.github.io/CommentCoreLibrary/docs/DoingItRight.html
Insert a comment with a border property into the manager and display it immediately for the user while syncing with the server.
```javascript
$('#send-button').click(function (){ // 为了简单采取类似 jQuery 的语法
var myCommentText = $('#danmaku-textarea').value;
// 检测以下是不是可以发
if (myCommentText.length === 0 || !canSend(myCommentText)) {
$('#user-notice').showNotice('弹幕空或者不符合规定'); // 提醒用户
return; // 取消发送
}
var comment = {
'text': myCommentText,
'stime': video.currentTime * 1000 - 1, // 比现在时间稍微慢一ms
'mode': 1,
'color': 0xffffff,
'border': true
};
CM.time(video.currentTime * 1000) // 强行更新以下 CM 的时间戳
CM.insert(comment); // 插入这个弹幕,因为时间 < CM内现在播放时间,所以一定不会被显示
sendCommentToServer(comment); // 把弹幕发到服务器上,注意服务器要无视 border=true 的
CM.send(comment); // 立刻显示一次自己这条弹幕,保证用户肯定会看到
//由于弹幕也被插入了 timeline, 如果用户回看,会发现弹幕依然带边框
});
```
--------------------------------
### Rotation Property Definition
Source: https://jabbany.github.io/CommentCoreLibrary/docs/CommentProperties.html
Defines the rX, rY, and rZ properties for 3D rotation.
```text
类型限制:mode > 6 弹幕旋转,定义3D旋转效果。分别是沿X,Y,Z轴旋转。
```
--------------------------------
### distance(x1:number, y1:number, x2:number, y2:number):number
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/Utils
Calculates the distance between two points.
```APIDOC
## distance(x1:number, y1:number, x2:number, y2:number):number
### Description
Calculates the distance difference between two coordinate points (x1, y1) and (x2, y2).
### Parameters
- **x1, y1** (number) - Required - Coordinates of the first point.
- **x2, y2** (number) - Required - Coordinates of the second point.
### Returns
- (number) - The calculated distance.
```
--------------------------------
### hue(h:number, s:number, v:number):number
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/Utils
Converts HSV color values to an RGB number.
```APIDOC
## hue(h:number, s:number = 1, v:number = 1):number
### Description
Converts HSV (Hue, Saturation, Value) color space values to an RGB integer. Saturation and brightness default to 1.
### Parameters
- **h** (number) - Required - Hue value.
- **s** (number) - Optional - Saturation value (default: 1).
- **v** (number) - Optional - Brightness/Value (default: 1).
### Returns
- (number) - The resulting RGB color value.
```
--------------------------------
### rand(min:number, max:number):number
Source: https://jabbany.github.io/CommentCoreLibrary/docs/scripting/Utils
Generates a random integer within a specified range.
```APIDOC
## rand(min:number, max:number):number
### Description
Returns a random integer between the specified minimum and maximum values.
### Parameters
- **min** (number) - Required - The minimum value.
- **max** (number) - Required - The maximum value.
### Returns
- (number) - A random integer within the range.
```