├── dist ├── types │ ├── helper │ │ ├── event.d.ts │ │ ├── css.d.ts │ │ ├── stragy.d.ts │ │ └── index.d.ts │ ├── stragy │ │ ├── global.d.ts │ │ ├── scroll.d.ts │ │ ├── fixed.d.ts │ │ ├── css3.d.ts │ │ ├── canvas.d.ts │ │ └── index.d.ts │ ├── commander │ │ ├── canvas │ │ │ ├── index.d.ts │ │ │ ├── fixed-top.d.ts │ │ │ ├── fixed-bottom.d.ts │ │ │ ├── base-canvas.d.ts │ │ │ ├── base-fixed.d.ts │ │ │ └── rolling.d.ts │ │ ├── index.d.ts │ │ ├── css-renderer │ │ │ ├── index.d.ts │ │ │ ├── fixed-top.d.ts │ │ │ ├── fixed-bottom.d.ts │ │ │ ├── base-fixed.d.ts │ │ │ ├── base-css.d.ts │ │ │ └── rolling.d.ts │ │ └── base.d.ts │ ├── event │ │ └── index.d.ts │ ├── constants │ │ └── index.d.ts │ ├── event-emitter.d.ts │ ├── track.d.ts │ ├── barrage.d.ts │ ├── track-manager.d.ts │ ├── a-barrage.d.ts │ └── types │ │ └── index.d.ts └── barrage.es5.js ├── tslint.json ├── .gitignore ├── .editorconfig ├── src ├── commander │ ├── index.ts │ ├── canvas │ │ ├── index.ts │ │ ├── base-canvas.ts │ │ ├── fixed-top.ts │ │ ├── fixed-bottom.ts │ │ ├── base-fixed.ts │ │ └── rolling.ts │ ├── css-renderer │ │ ├── index.ts │ │ ├── fixed-top.ts │ │ ├── fixed-bottom.ts │ │ ├── base-fixed.ts │ │ ├── base-css.ts │ │ └── rolling.ts │ └── base.ts ├── stragy │ ├── index.ts │ ├── canvas.ts │ └── css3.ts ├── constants │ └── index.ts ├── track.ts ├── helper │ ├── css.ts │ └── index.ts ├── event-emitter.ts ├── event │ └── index.ts ├── types │ └── index.ts └── a-barrage.ts ├── tsconfig.json ├── .travis.yml ├── CONTRIBUTING.md ├── tools ├── gh-pages-publish.ts └── semantic-release-prepare.ts ├── LICENSE ├── example ├── src │ ├── index.js │ ├── css3 │ │ ├── index.html │ │ └── index.js │ ├── canvas │ │ ├── index.html │ │ └── index.js │ └── index.html ├── webpack.prod.js ├── webpack.config.js ├── css3.html ├── canvas.html ├── index.html └── index.bundle.js ├── rollup.config.ts ├── test ├── event-emitter.spec.ts └── helpers │ └── index.spec.ts ├── code-of-conduct.md ├── package.json └── README.md /dist/types/helper/event.d.ts: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint-config-standard", 4 | "tslint-config-prettier" 5 | ] 6 | } -------------------------------------------------------------------------------- /dist/types/stragy/global.d.ts: -------------------------------------------------------------------------------- 1 | declare const _default: { 2 | push(this: any): void; 3 | }; 4 | export default _default; 5 | -------------------------------------------------------------------------------- /dist/types/commander/canvas/index.d.ts: -------------------------------------------------------------------------------- 1 | import { RenderEngine } from '../../types'; 2 | declare const engine: RenderEngine; 3 | export default engine; 4 | -------------------------------------------------------------------------------- /dist/types/commander/index.d.ts: -------------------------------------------------------------------------------- 1 | import { RenderEngine } from '../types'; 2 | export declare function getEngine(type: string): RenderEngine | null; 3 | -------------------------------------------------------------------------------- /dist/types/commander/css-renderer/index.d.ts: -------------------------------------------------------------------------------- 1 | import { RenderEngine } from '../../types'; 2 | declare const engine: RenderEngine; 3 | export default engine; 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | .nyc_output 4 | .DS_Store 5 | *.log 6 | .vscode 7 | .idea 8 | compiled 9 | .awcache 10 | .rpt2_cache 11 | docs 12 | -------------------------------------------------------------------------------- /dist/types/event/index.d.ts: -------------------------------------------------------------------------------- 1 | import BarrageMaker from '../a-barrage'; 2 | export declare function injectNativeEvents(instance: BarrageMaker): void; 3 | export declare function injectEventsDelegator(instance: BarrageMaker): void; 4 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | #root = true 2 | 3 | [*] 4 | indent_style = space 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | max_line_length = 100 10 | indent_size = 2 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /dist/types/stragy/scroll.d.ts: -------------------------------------------------------------------------------- 1 | import { ScrollBarrageObject } from '../types'; 2 | declare const _default: { 3 | add(this: any, barrage: ScrollBarrageObject): boolean; 4 | find(this: any): number; 5 | push(this: any): void; 6 | render(this: any): void; 7 | }; 8 | export default _default; 9 | -------------------------------------------------------------------------------- /dist/types/commander/css-renderer/fixed-top.d.ts: -------------------------------------------------------------------------------- 1 | import BaseFixedCommander from './base-fixed'; 2 | import { CommanderConfig } from '../../types'; 3 | export default class FixedTopCommander extends BaseFixedCommander { 4 | constructor(el: HTMLDivElement, config: CommanderConfig); 5 | render(): void; 6 | } 7 | -------------------------------------------------------------------------------- /dist/types/stragy/fixed.d.ts: -------------------------------------------------------------------------------- 1 | import { FixedBarrageObejct } from '../types'; 2 | declare const _default: { 3 | add(this: any, barrage: FixedBarrageObejct): boolean; 4 | find(this: any): number; 5 | renderTop(this: any): void; 6 | renderBottom(this: any): void; 7 | }; 8 | export default _default; 9 | -------------------------------------------------------------------------------- /dist/types/commander/canvas/fixed-top.d.ts: -------------------------------------------------------------------------------- 1 | import BaseFixedCommander from './base-fixed'; 2 | import { CommanderConfig } from '../../types'; 3 | export default class FixedTopCommander extends BaseFixedCommander { 4 | constructor(canvas: HTMLCanvasElement, config: CommanderConfig); 5 | render(): void; 6 | } 7 | -------------------------------------------------------------------------------- /dist/types/commander/css-renderer/fixed-bottom.d.ts: -------------------------------------------------------------------------------- 1 | import BaseFixedCommander from './base-fixed'; 2 | import { CommanderConfig } from '../../types'; 3 | export default class FixedTopCommander extends BaseFixedCommander { 4 | constructor(el: HTMLDivElement, config: CommanderConfig); 5 | render(): void; 6 | } 7 | -------------------------------------------------------------------------------- /dist/types/commander/canvas/fixed-bottom.d.ts: -------------------------------------------------------------------------------- 1 | import BaseFixedCommander from './base-fixed'; 2 | import { CommanderConfig } from '../../types'; 3 | export default class FixedBottomCommander extends BaseFixedCommander { 4 | constructor(canvas: HTMLCanvasElement, config: CommanderConfig); 5 | render(): void; 6 | } 7 | -------------------------------------------------------------------------------- /src/commander/index.ts: -------------------------------------------------------------------------------- 1 | import CanvasEngine from './canvas' 2 | import CssEngine from './css-renderer' 3 | import { RenderEngine } from '../types' 4 | 5 | export function getEngine(type: 'canvas' | 'css3'): RenderEngine { 6 | if (type === 'canvas') { 7 | return CanvasEngine 8 | } 9 | return CssEngine 10 | } 11 | -------------------------------------------------------------------------------- /dist/types/stragy/css3.d.ts: -------------------------------------------------------------------------------- 1 | import BarrageMaker from '../a-barrage'; 2 | import { RawBarrageObject, CommanderMapKey } from '../types'; 3 | declare const _default: { 4 | clear(this: BarrageMaker): void; 5 | add(this: BarrageMaker, barrage: RawBarrageObject, type?: CommanderMapKey): void; 6 | _render(this: BarrageMaker): void; 7 | }; 8 | export default _default; 9 | -------------------------------------------------------------------------------- /dist/types/stragy/canvas.d.ts: -------------------------------------------------------------------------------- 1 | import BarrageMaker from '../a-barrage'; 2 | import { RawBarrageObject, CommanderMapKey } from '../types'; 3 | declare const _default: { 4 | clear(this: BarrageMaker): void; 5 | add(this: BarrageMaker, barrage: RawBarrageObject, type?: CommanderMapKey): void; 6 | _render(this: BarrageMaker): void; 7 | }; 8 | export default _default; 9 | -------------------------------------------------------------------------------- /src/commander/canvas/index.ts: -------------------------------------------------------------------------------- 1 | import FixedTopCommander from './fixed-top' 2 | import FixedBottomCommander from './fixed-bottom' 3 | import RollingCommander from './rolling' 4 | import { RenderEngine } from '../../types' 5 | 6 | const engine: RenderEngine = { 7 | FixedBottomCommander, 8 | FixedTopCommander, 9 | RollingCommander 10 | } 11 | 12 | export default engine 13 | -------------------------------------------------------------------------------- /src/commander/css-renderer/index.ts: -------------------------------------------------------------------------------- 1 | import FixedTopCommander from './fixed-top' 2 | import RollingCommander from './rolling' 3 | import FixedBottomCommander from './fixed-bottom' 4 | import { RenderEngine } from '../../types' 5 | 6 | const engine: RenderEngine = { 7 | FixedTopCommander, 8 | FixedBottomCommander, 9 | RollingCommander 10 | } 11 | 12 | export default engine 13 | -------------------------------------------------------------------------------- /dist/types/constants/index.d.ts: -------------------------------------------------------------------------------- 1 | import { CommanderMapKey } from '../types'; 2 | export declare const HTML_ELEMENT_NATIVE_EVENTS: string[]; 3 | interface BarrageTypeObject { 4 | SCROLL: CommanderMapKey; 5 | FIXED_TOP: CommanderMapKey; 6 | FIXED_BOTTOM: CommanderMapKey; 7 | } 8 | export declare const BARRAGE_TYPE: BarrageTypeObject; 9 | export declare const TIME_PER_FRAME = 16.6; 10 | export {}; 11 | -------------------------------------------------------------------------------- /dist/types/event-emitter.d.ts: -------------------------------------------------------------------------------- 1 | interface EventHandler { 2 | (...args: any[]): any; 3 | } 4 | export default class EventEmitter { 5 | private _eventsMap; 6 | $on(eventName: string, handler: EventHandler): this; 7 | $once(eventName: string, handler: EventHandler): this; 8 | $off(eventName: string, handler?: EventHandler): this; 9 | $emit(eventName: string, ...args: any[]): void; 10 | } 11 | export {}; 12 | -------------------------------------------------------------------------------- /dist/types/commander/canvas/base-canvas.d.ts: -------------------------------------------------------------------------------- 1 | import BaseCommander from '../base'; 2 | import { BarrageObject, CommanderConfig } from '../../types'; 3 | export default abstract class BaseCanvasCommander extends BaseCommander { 4 | protected canvas: HTMLCanvasElement; 5 | protected ctx: CanvasRenderingContext2D; 6 | constructor(canvas: HTMLCanvasElement, config: CommanderConfig); 7 | reset(): void; 8 | } 9 | -------------------------------------------------------------------------------- /dist/types/commander/canvas/base-fixed.d.ts: -------------------------------------------------------------------------------- 1 | import BaseCanvasCommander from './base-canvas'; 2 | import { FixedBarrageObejct, CommanderConfig } from '../../types'; 3 | export default abstract class BaseFixedCommander extends BaseCanvasCommander { 4 | constructor(canvas: HTMLCanvasElement, config: CommanderConfig); 5 | add(barrage: FixedBarrageObejct): boolean; 6 | _findTrack(): number; 7 | _extractBarrage(): void; 8 | } 9 | -------------------------------------------------------------------------------- /dist/types/stragy/index.d.ts: -------------------------------------------------------------------------------- 1 | import { RawBarrageObject, CommanderMapKey } from '../types'; 2 | export interface FnMap { 3 | clear(): void; 4 | add(barrage: RawBarrageObject, type: CommanderMapKey): void; 5 | _render(): void; 6 | } 7 | declare type FnMapKey = keyof FnMap; 8 | export declare function getHandler(engine: 'canvas' | 'css3', fn: FnMapKey): (() => void) | ((barrage: RawBarrageObject, type: "scroll" | "fixed-top" | "fixed-bottom") => void) | (() => void); 9 | export {}; 10 | -------------------------------------------------------------------------------- /dist/types/helper/css.d.ts: -------------------------------------------------------------------------------- 1 | export declare function createElement(tagName: string): HTMLElement; 2 | export declare function createBarrage(text: string, color: string, fontSize: string, left: string): HTMLElement; 3 | export declare function appendChild(parent: HTMLElement, child: HTMLElement): HTMLElement; 4 | export declare function setStyle(el: HTMLElement, style: Partial): void; 5 | export declare function setHoverStyle(el: HTMLElement): void; 6 | export declare function setBlurStyle(el: HTMLElement): void; 7 | -------------------------------------------------------------------------------- /dist/types/track.d.ts: -------------------------------------------------------------------------------- 1 | import { BarrageObject } from './types'; 2 | interface TrackForEachHandler { 3 | (track: T, index: number, array: T[]): void; 4 | } 5 | export default class BarrageTrack { 6 | barrages: T[]; 7 | offset: number; 8 | forEach(handler: TrackForEachHandler): void; 9 | reset(): void; 10 | push(...items: T[]): void; 11 | removeTop(): void; 12 | remove(index: number): void; 13 | updateOffset(): void; 14 | } 15 | export {}; 16 | -------------------------------------------------------------------------------- /src/stragy/index.ts: -------------------------------------------------------------------------------- 1 | import { RawBarrageObject, CommanderMapKey } from '../types' 2 | import CanvasStragy from './canvas' 3 | import Css3Stragy from './css3' 4 | 5 | export interface FnMap { 6 | clear(): void 7 | add(barrage: RawBarrageObject, type: CommanderMapKey): void 8 | _render(): void 9 | } 10 | 11 | type FnMapKey = keyof FnMap 12 | 13 | export function getHandler(engine: 'canvas' | 'css3', fn: FnMapKey) { 14 | const fnMap: FnMap = engine === 'canvas' ? CanvasStragy : Css3Stragy 15 | return fnMap[fn] 16 | } 17 | -------------------------------------------------------------------------------- /dist/types/commander/canvas/rolling.d.ts: -------------------------------------------------------------------------------- 1 | import BaseCanvasCommander from './base-canvas'; 2 | import { ScrollBarrageObject, CommanderConfig } from '../../types'; 3 | export default class RollingCommander extends BaseCanvasCommander { 4 | constructor(canvas: HTMLCanvasElement, config: CommanderConfig); 5 | private get _defaultSpeed(); 6 | private get _randomSpeed(); 7 | add(barrage: ScrollBarrageObject): boolean; 8 | _findTrack(): number; 9 | _extractBarrage(): void; 10 | render(): void; 11 | } 12 | -------------------------------------------------------------------------------- /src/constants/index.ts: -------------------------------------------------------------------------------- 1 | import { CommanderMapKey } from '../types' 2 | 3 | export const HTML_ELEMENT_NATIVE_EVENTS = 'click,dblclick,mousedown,mousemove,mouseout,mouseover,mouseup'.split( 4 | ',' 5 | ) 6 | 7 | interface BarrageTypeObject { 8 | SCROLL: CommanderMapKey 9 | FIXED_TOP: CommanderMapKey 10 | FIXED_BOTTOM: CommanderMapKey 11 | } 12 | 13 | export const BARRAGE_TYPE: BarrageTypeObject = { 14 | SCROLL: 'scroll', 15 | FIXED_TOP: 'fixed-top', 16 | FIXED_BOTTOM: 'fixed-bottom' 17 | } 18 | 19 | export const TIME_PER_FRAME = 16.6 20 | -------------------------------------------------------------------------------- /dist/types/helper/stragy.d.ts: -------------------------------------------------------------------------------- 1 | import { BarrageObject } from '../types'; 2 | import TrackManager from '../track-manager'; 3 | export declare const addBarrageStragy: { 4 | [x: string]: (this: TrackManager, barrage: BarrageObject) => boolean; 5 | }; 6 | export declare const findTrackStragy: { 7 | [x: string]: (this: TrackManager) => number; 8 | }; 9 | export declare const pushBarrageStragy: { 10 | [x: string]: (this: TrackManager) => void; 11 | }; 12 | export declare const renderBarrageStragy: { 13 | [x: string]: (this: TrackManager) => void; 14 | }; 15 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "node", 4 | "target": "es5", 5 | "module":"es2015", 6 | "lib": ["es2015", "es2016", "es2017", "dom"], 7 | "strict": true, 8 | "sourceMap": true, 9 | "declaration": true, 10 | "allowSyntheticDefaultImports": true, 11 | "experimentalDecorators": true, 12 | "emitDecoratorMetadata": true, 13 | "declarationDir": "dist/types", 14 | "outDir": "dist/lib", 15 | "typeRoots": [ 16 | "node_modules/@types" 17 | ] 18 | }, 19 | "include": [ 20 | "src" 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /dist/types/commander/css-renderer/base-fixed.d.ts: -------------------------------------------------------------------------------- 1 | import BaseCssCommander from './base-css'; 2 | import { CommanderConfig, FixedBarrageObejct } from '../../types'; 3 | import Track from '../../track'; 4 | export default abstract class BaseFixedCssCommander extends BaseCssCommander { 5 | protected elHeight: number; 6 | constructor(el: HTMLDivElement, config: CommanderConfig); 7 | add(barrage: FixedBarrageObejct): boolean; 8 | _findTrack(): number; 9 | _extractBarrage(): void; 10 | _removeTopElementFromTrack(track: Track): void; 11 | } 12 | -------------------------------------------------------------------------------- /src/commander/canvas/base-canvas.ts: -------------------------------------------------------------------------------- 1 | import BaseCommander from '../base' 2 | import { BarrageObject, CommanderConfig } from '../../types' 3 | 4 | export default abstract class BaseCanvasCommander extends BaseCommander< 5 | T 6 | > { 7 | protected canvas: HTMLCanvasElement 8 | protected ctx: CanvasRenderingContext2D 9 | 10 | constructor(canvas: HTMLCanvasElement, config: CommanderConfig) { 11 | super(config) 12 | this.canvas = canvas 13 | this.ctx = canvas.getContext('2d')! 14 | } 15 | 16 | reset() { 17 | this.forEach(track => track.reset()) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /dist/types/commander/css-renderer/base-css.d.ts: -------------------------------------------------------------------------------- 1 | import BaseCommander from '../base'; 2 | import { BarrageObject, CommanderConfig } from '../../types'; 3 | export default abstract class BaseCssCommander extends BaseCommander { 4 | el: HTMLDivElement; 5 | objToElm: WeakMap; 6 | elmToObj: WeakMap; 7 | freezeBarrage: T | null; 8 | constructor(el: HTMLDivElement, config: CommanderConfig); 9 | removeElement(target: HTMLElement): void; 10 | _mouseMoveEventHandler(e: Event): void; 11 | _mouseClickEventHandler(e: Event): void; 12 | reset(): void; 13 | } 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | cache: 3 | directories: 4 | - ~/.npm 5 | notifications: 6 | email: false 7 | node_js: 8 | - '10' 9 | - '11' 10 | - '8' 11 | - '6' 12 | script: 13 | - npm run test:prod && npm run build 14 | after_success: 15 | - npm run travis-deploy-once "npm run report-coverage" 16 | - if [ "$TRAVIS_BRANCH" = "master" -a "$TRAVIS_PULL_REQUEST" = "false" ]; then npm run travis-deploy-once "npm run deploy-docs"; fi 17 | - if [ "$TRAVIS_BRANCH" = "master" -a "$TRAVIS_PULL_REQUEST" = "false" ]; then npm run travis-deploy-once "npm run semantic-release"; fi 18 | branches: 19 | except: 20 | - /^v\d+\.\d+\.\d+$/ 21 | -------------------------------------------------------------------------------- /dist/types/commander/css-renderer/rolling.d.ts: -------------------------------------------------------------------------------- 1 | import BaseCssCommander from './base-css'; 2 | import { ScrollBarrageObject, CommanderConfig } from '../../types'; 3 | import Track from '../../track'; 4 | export default class RollingCssCommander extends BaseCssCommander { 5 | constructor(el: HTMLDivElement, config: CommanderConfig); 6 | private get _defaultSpeed(); 7 | private get _randomSpeed(); 8 | add(barrage: ScrollBarrageObject): boolean; 9 | _findTrack(): number; 10 | _extractBarrage(): void; 11 | render(): void; 12 | _removeElementFromTrack(track: Track, removedIndex: number): void; 13 | } 14 | -------------------------------------------------------------------------------- /dist/types/commander/base.d.ts: -------------------------------------------------------------------------------- 1 | import { BarrageObject, CommanderConfig } from '../types'; 2 | import Track from '../track'; 3 | import EventEmitter from '../event-emitter'; 4 | interface CommanderForEachHandler { 5 | (track: Track, index: number, array: Track[]): void; 6 | } 7 | export default abstract class BaseCommander extends EventEmitter { 8 | protected trackWidth: number; 9 | protected trackHeight: number; 10 | protected duration: number; 11 | protected maxTrack: number; 12 | protected tracks: Track[]; 13 | waitingQueue: T[]; 14 | constructor(config: CommanderConfig); 15 | forEach(handler: CommanderForEachHandler): void; 16 | resize(width?: number, height?: number): void; 17 | abstract add(barrage: T): boolean; 18 | abstract _findTrack(): number; 19 | abstract _extractBarrage(): void; 20 | abstract render(): void; 21 | abstract reset(): void; 22 | } 23 | export {}; 24 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | We're really glad you're reading this, because we need volunteer developers to help this project come to fruition. 👏 2 | 3 | ## Instructions 4 | 5 | These steps will guide you through contributing to this project: 6 | 7 | - Fork the repo 8 | - Clone it and install dependencies 9 | 10 | git clone https://github.com/YOUR-USERNAME/typescript-library-starter 11 | npm install 12 | 13 | Keep in mind that after running `npm install` the git repo is reset. So a good way to cope with this is to have a copy of the folder to push the changes, and the other to try them. 14 | 15 | Make and commit your changes. Make sure the commands npm run build and npm run test:prod are working. 16 | 17 | Finally send a [GitHub Pull Request](https://github.com/alexjoverm/typescript-library-starter/compare?expand=1) with a clear list of what you've done (read more [about pull requests](https://help.github.com/articles/about-pull-requests/)). Make sure all of your commits are atomic (one feature per commit). 18 | -------------------------------------------------------------------------------- /src/commander/canvas/fixed-top.ts: -------------------------------------------------------------------------------- 1 | import BaseFixedCommander from './base-fixed' 2 | import { TIME_PER_FRAME } from '../../constants' 3 | import { CommanderConfig } from '../../types' 4 | 5 | export default class FixedTopCommander extends BaseFixedCommander { 6 | constructor(canvas: HTMLCanvasElement, config: CommanderConfig) { 7 | super(canvas, config) 8 | } 9 | 10 | render(): void { 11 | this._extractBarrage() 12 | const ctx = this.ctx 13 | const trackHeight = this.trackHeight 14 | this.tracks.forEach((track, index) => { 15 | const barrage = track.barrages[0] 16 | if (!barrage) { 17 | return 18 | } 19 | const { color, text, offset, size } = barrage 20 | ctx.fillStyle = color 21 | ctx.font = `${size}px 'Microsoft Yahei'` 22 | ctx.fillText(text, offset, (index + 1) * trackHeight) 23 | barrage.duration -= TIME_PER_FRAME 24 | if (barrage.duration <= 0) { 25 | track.removeTop() 26 | } 27 | }) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tools/gh-pages-publish.ts: -------------------------------------------------------------------------------- 1 | const { cd, exec, echo, touch } = require("shelljs") 2 | const { readFileSync } = require("fs") 3 | const url = require("url") 4 | 5 | let repoUrl 6 | let pkg = JSON.parse(readFileSync("package.json") as any) 7 | if (typeof pkg.repository === "object") { 8 | if (!pkg.repository.hasOwnProperty("url")) { 9 | throw new Error("URL does not exist in repository section") 10 | } 11 | repoUrl = pkg.repository.url 12 | } else { 13 | repoUrl = pkg.repository 14 | } 15 | 16 | let parsedUrl = url.parse(repoUrl) 17 | let repository = (parsedUrl.host || "") + (parsedUrl.path || "") 18 | let ghToken = process.env.GH_TOKEN 19 | 20 | echo("Deploying docs!!!") 21 | cd("docs") 22 | touch(".nojekyll") 23 | exec("git init") 24 | exec("git add .") 25 | exec('git config user.name "everlastlucas"') 26 | exec('git config user.email "everlastlucas@outlook.com"') 27 | exec('git commit -m "docs(docs): update gh-pages"') 28 | exec( 29 | `git push --force --quiet "https://${ghToken}@${repository}" master:gh-pages` 30 | ) 31 | echo("Docs deployed!!") 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 everlastlucas 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /example/src/index.js: -------------------------------------------------------------------------------- 1 | import Barrage from '../../dist/barrage.umd'; 2 | 3 | function getRandomWord() { 4 | const words = [ 5 | 'Thanks for visiting!', 6 | 'ABarrage弹幕库', 7 | '干杯!!!🍻' 8 | ]; 9 | const index = Math.floor(Math.random() * 3); 10 | return words[index]; 11 | } 12 | 13 | function mockBarrage() { 14 | return { 15 | text: getRandomWord(), 16 | color: '#fff' 17 | }; 18 | } 19 | 20 | const $ = (selector) => document.querySelector(selector); 21 | 22 | const danmu = $('#danmu'); 23 | const barrage = new Barrage(danmu, { 24 | fontSize: 40, 25 | duration: 8000, 26 | trackHeight: 40 * 1.5, 27 | engine: 'canvas', 28 | usePointerEvents: true 29 | }); 30 | 31 | const buildBarrageHandler = () => { 32 | const BUILD_COUNT = 20; 33 | for(let i = 0;i < BUILD_COUNT; ++i) { 34 | const text = mockBarrage(); 35 | barrage.add(text, 'scroll'); 36 | } 37 | setTimeout(buildBarrageHandler, 5000); 38 | }; 39 | 40 | buildBarrageHandler(); 41 | 42 | const rect = document.body.getBoundingClientRect(); 43 | danmu.width = rect.width; 44 | danmu.height = rect.height; 45 | 46 | barrage.start(); -------------------------------------------------------------------------------- /src/commander/canvas/fixed-bottom.ts: -------------------------------------------------------------------------------- 1 | import BaseFixedCommander from './base-fixed' 2 | import { TIME_PER_FRAME } from '../../constants' 3 | import { CommanderConfig } from '../../types' 4 | 5 | export default class FixedBottomCommander extends BaseFixedCommander { 6 | constructor(canvas: HTMLCanvasElement, config: CommanderConfig) { 7 | super(canvas, config) 8 | } 9 | 10 | render(): void { 11 | this._extractBarrage() 12 | const ctx = this.ctx 13 | const trackHeight = this.trackHeight 14 | const canvasHeight = this.canvas.height 15 | const startY = canvasHeight - this.trackHeight * this.tracks.length 16 | this.tracks.forEach((track, index) => { 17 | const barrage = track.barrages[0] 18 | if (!barrage) { 19 | return 20 | } 21 | const { color, text, offset, size } = barrage 22 | ctx.fillStyle = color 23 | ctx.font = `${size}px 'Microsoft Yahei'` 24 | ctx.fillText(text, offset, startY + index * trackHeight) 25 | barrage.duration -= TIME_PER_FRAME 26 | if (barrage.duration <= 0) { 27 | track.removeTop() 28 | } 29 | }) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/commander/css-renderer/fixed-top.ts: -------------------------------------------------------------------------------- 1 | import BaseFixedCommander from './base-fixed' 2 | import { TIME_PER_FRAME } from '../../constants' 3 | import { CommanderConfig } from '../../types' 4 | 5 | export default class FixedTopCommander extends BaseFixedCommander { 6 | constructor(el: HTMLDivElement, config: CommanderConfig) { 7 | super(el, config) 8 | } 9 | 10 | render(): void { 11 | this._extractBarrage() 12 | const objToElm = this.objToElm 13 | const trackHeight = this.trackHeight 14 | this.tracks.forEach((track, trackIndex) => { 15 | const barrage = track.barrages[0] 16 | if (!barrage) { 17 | return 18 | } 19 | const el = objToElm.get(barrage) 20 | if (!el) { 21 | return 22 | } 23 | if (barrage.freeze) { 24 | return 25 | } 26 | const { offset } = barrage 27 | const y = trackIndex * trackHeight 28 | el.style.transform = `translate(${offset}px, ${y}px)` 29 | barrage.duration -= TIME_PER_FRAME 30 | if (barrage.duration <= 0) { 31 | this._removeTopElementFromTrack(track) 32 | track.removeTop() 33 | } 34 | }) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/track.ts: -------------------------------------------------------------------------------- 1 | import { BarrageObject } from './types' 2 | import { isScrollBarrage } from './helper' 3 | 4 | interface TrackForEachHandler { 5 | (track: T, index: number, array: T[]): void 6 | } 7 | 8 | export default class BarrageTrack { 9 | barrages: T[] = [] 10 | offset: number = 0 11 | 12 | forEach(handler: TrackForEachHandler) { 13 | for (let i = 0; i < this.barrages.length; ++i) { 14 | handler(this.barrages[i], i, this.barrages) 15 | } 16 | } 17 | 18 | reset() { 19 | this.barrages = [] 20 | this.offset = 0 21 | } 22 | 23 | push(...items: T[]) { 24 | this.barrages.push(...items) 25 | } 26 | 27 | removeTop() { 28 | this.barrages.shift() 29 | } 30 | 31 | remove(index: number) { 32 | if (index < 0 || index >= this.barrages.length) { 33 | return 34 | } 35 | this.barrages.splice(index, 1) 36 | } 37 | 38 | updateOffset() { 39 | const endBarrage = this.barrages[this.barrages.length - 1] 40 | if (endBarrage && isScrollBarrage(endBarrage)) { 41 | const { speed } = endBarrage 42 | this.offset -= speed 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /dist/types/barrage.d.ts: -------------------------------------------------------------------------------- 1 | import { BarrageConfig, RawBarrageObject, TrackManagerMap, TrackManagerMapKey, ScrollBarrageObject, FixedBarrageObejct } from './types'; 2 | import TrackManager from './track-manager'; 3 | import EventEmitter from './event-emitter'; 4 | declare type BarrageConfigInit = Partial; 5 | export default class BarrageMaker extends EventEmitter { 6 | el: HTMLElement; 7 | canvas: HTMLCanvasElement; 8 | ctx: CanvasRenderingContext2D; 9 | config: BarrageConfig; 10 | trackManagerMap: TrackManagerMap; 11 | animation: number | null; 12 | constructor(wrapper: HTMLElement | string, config?: BarrageConfigInit); 13 | resize(width?: number, height?: number): void; 14 | clear(): void; 15 | setOpacity(opacity?: number): void; 16 | setFontSize(zoom?: number): void; 17 | add(barrage: RawBarrageObject, type?: TrackManagerMapKey): void; 18 | start(): void; 19 | stop(): void; 20 | _forEachManager(handler: (trackManager: TrackManager | TrackManager) => any): void; 21 | _render(): void; 22 | _bindNativeEvents(): void; 23 | _delegateEvents(): void; 24 | } 25 | export {}; 26 | -------------------------------------------------------------------------------- /dist/types/track-manager.d.ts: -------------------------------------------------------------------------------- 1 | import Track from './track'; 2 | import { BarrageObject } from './types'; 3 | interface TrackManagerForEachHandler { 4 | (track: Track, index: number, array: Track[]): void; 5 | } 6 | declare type BarrageType = 'scroll' | 'fixed-top' | 'fixed-bottom'; 7 | interface TrackManagerConfig { 8 | trackWidth: number; 9 | trackHeight: number; 10 | duration: number; 11 | numbersOfTrack: number; 12 | type: BarrageType; 13 | } 14 | export default class TrackManager { 15 | canvas: HTMLCanvasElement; 16 | context: CanvasRenderingContext2D; 17 | trackWidth: number; 18 | trackHeight: number; 19 | tracks: Track[]; 20 | duration: number; 21 | type: BarrageType; 22 | waitingQueue: T[]; 23 | constructor(canvas: HTMLCanvasElement, config: TrackManagerConfig); 24 | forEach(handler: TrackManagerForEachHandler): void; 25 | add(barrage: T): any; 26 | _findMatchestTrack(): number; 27 | _pushBarrage(): any; 28 | render(): void; 29 | get _defaultSpeed(): number; 30 | get _randomSpeed(): number; 31 | reset(): void; 32 | resize(trackWidth?: number, trackHeight?: number): void; 33 | } 34 | export {}; 35 | -------------------------------------------------------------------------------- /dist/types/helper/index.d.ts: -------------------------------------------------------------------------------- 1 | import { ScrollBarrageObject, FixedBarrageObejct } from '../types'; 2 | export declare function isEmptyArray(array: T[]): boolean; 3 | export declare function getArrayRight(array: T[]): T; 4 | export declare function isDiv(el: any): el is HTMLDivElement; 5 | export declare function isCanvas(el: any): el is HTMLCanvasElement; 6 | export declare function getEl(el: HTMLDivElement | HTMLCanvasElement | string, type: 'css3' | 'canvas'): HTMLDivElement | HTMLCanvasElement; 7 | export declare const requestAnimationFrame: ((callback: FrameRequestCallback) => number) & typeof globalThis.requestAnimationFrame; 8 | export declare const cancelAnimationFrame: ((handle: number) => void) & typeof globalThis.cancelAnimationFrame; 9 | export declare const isFunction: (fn: any) => fn is Function; 10 | export declare const isNull: (o: any) => o is null; 11 | export declare const isUndefined: (o: any) => o is undefined; 12 | export declare const isObject: (o: any) => o is object; 13 | export declare const isPlainObject: (o: any) => o is object; 14 | export declare function deepMerge(...objects: any[]): any; 15 | export declare function isScrollBarrage(x: any): x is ScrollBarrageObject; 16 | export declare function isFixedBarrage(x: any): x is FixedBarrageObejct; 17 | -------------------------------------------------------------------------------- /src/commander/css-renderer/fixed-bottom.ts: -------------------------------------------------------------------------------- 1 | import BaseFixedCommander from './base-fixed' 2 | import { TIME_PER_FRAME } from '../../constants' 3 | import { CommanderConfig } from '../../types' 4 | 5 | export default class FixedTopCommander extends BaseFixedCommander { 6 | constructor(el: HTMLDivElement, config: CommanderConfig) { 7 | super(el, config) 8 | } 9 | 10 | render(): void { 11 | this._extractBarrage() 12 | const objToElm = this.objToElm 13 | const trackHeight = this.trackHeight 14 | const maxTrack = this.maxTrack 15 | const elHeight = this.el.offsetHeight 16 | const yBase = elHeight - maxTrack * trackHeight 17 | this.tracks.forEach((track, trackIndex) => { 18 | const barrage = track.barrages[0] 19 | if (!barrage) { 20 | return 21 | } 22 | const el = objToElm.get(barrage) 23 | if (!el) { 24 | return 25 | } 26 | if (barrage.freeze) { 27 | return 28 | } 29 | const { offset } = barrage 30 | const y = yBase + trackIndex * trackHeight 31 | el.style.transform = `translate(${offset}px, ${y}px)` 32 | barrage.duration -= TIME_PER_FRAME 33 | if (barrage.duration <= 0) { 34 | this._removeTopElementFromTrack(track) 35 | track.removeTop() 36 | } 37 | }) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/helper/css.ts: -------------------------------------------------------------------------------- 1 | export function createElement(tagName: string) { 2 | return document.createElement(tagName) 3 | } 4 | 5 | export function createBarrage( 6 | text: string, 7 | color: string, 8 | fontSize: string, 9 | left: string, 10 | el?: HTMLElement 11 | ) { 12 | const danmu = el || createElement('div') 13 | setStyle(danmu, { 14 | position: 'absolute', 15 | color, 16 | fontSize, 17 | transform: `translateX(${left}px)`, 18 | textShadow: '#000 1px 0 0, #000 0 1px 0, #000 -1px 0 0, #000 0 -1px 0', 19 | pointerEvents: 'auto', 20 | padding: '3px 20px', 21 | borderRadius: '20px', 22 | backgroundColor: 'transparent' 23 | }) 24 | danmu.textContent = text 25 | return danmu 26 | } 27 | 28 | export function appendChild(parent: HTMLElement, child: HTMLElement) { 29 | return parent.appendChild(child) 30 | } 31 | 32 | export function setStyle(el: HTMLElement, style: Partial) { 33 | for (const key in style) { 34 | el.style[key] = style[key]! 35 | } 36 | } 37 | 38 | export function setHoverStyle(el: HTMLElement) { 39 | el.style.backgroundColor = 'rgba(0, 0, 0, 0.5)' 40 | el.style.cursor = 'pointer' 41 | } 42 | 43 | export function setBlurStyle(el: HTMLElement) { 44 | el.style.backgroundColor = 'transparent' 45 | el.style.cursor = 'auto' 46 | } 47 | -------------------------------------------------------------------------------- /rollup.config.ts: -------------------------------------------------------------------------------- 1 | import resolve from 'rollup-plugin-node-resolve' 2 | import commonjs from 'rollup-plugin-commonjs' 3 | import sourceMaps from 'rollup-plugin-sourcemaps' 4 | import camelCase from 'lodash.camelcase' 5 | import typescript from 'rollup-plugin-typescript2' 6 | import json from 'rollup-plugin-json' 7 | 8 | const pkg = require('./package.json') 9 | 10 | const libraryName = 'a-barrage' 11 | 12 | export default { 13 | input: `src/${libraryName}.ts`, 14 | output: [ 15 | { file: pkg.main, name: 'ABarrage', format: 'umd', sourcemap: true }, 16 | { file: pkg.module, format: 'es', sourcemap: true }, 17 | ], 18 | // Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash') 19 | external: [], 20 | watch: { 21 | include: 'src/**', 22 | }, 23 | plugins: [ 24 | // Allow json resolution 25 | json(), 26 | // Compile TypeScript files 27 | typescript({ useTsconfigDeclarationDir: true }), 28 | // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs) 29 | commonjs(), 30 | // Allow node_modules resolution, so you can use 'external' to control 31 | // which external modules to include in the bundle 32 | // https://github.com/rollup/rollup-plugin-node-resolve#usage 33 | resolve(), 34 | 35 | // Resolve source maps to the original source 36 | sourceMaps(), 37 | ], 38 | } 39 | -------------------------------------------------------------------------------- /dist/types/a-barrage.d.ts: -------------------------------------------------------------------------------- 1 | import { BarrageConfig, RawBarrageObject, CommanderMap, CommanderMapKey, ScrollBarrageObject, FixedBarrageObejct, BarrageMouseEventHandler } from './types'; 2 | import EventEmitter from './event-emitter'; 3 | import BaseCommander from './commander/base'; 4 | declare type BarrageConfigInit = Partial; 5 | export default class BarrageMaker extends EventEmitter { 6 | el: HTMLDivElement | HTMLCanvasElement; 7 | canvas: HTMLCanvasElement | null; 8 | ctx: CanvasRenderingContext2D | null; 9 | config: BarrageConfig; 10 | commanderMap: CommanderMap; 11 | animation: number | null; 12 | constructor(el: HTMLDivElement | HTMLCanvasElement | string, config?: BarrageConfigInit); 13 | resize(width?: number): void; 14 | clear(): void; 15 | setOpacity(opacity?: number): void; 16 | setFontSize(zoom?: number): void; 17 | add(barrage: RawBarrageObject, type?: CommanderMapKey): void; 18 | start(): void; 19 | stop(): void; 20 | onBarrageHover(handler: BarrageMouseEventHandler): void; 21 | onBarrageBlur(handler: BarrageMouseEventHandler): void; 22 | onBarrageClick(handler: BarrageMouseEventHandler): void; 23 | _bindBarrageEvent(eventName: string, handler: BarrageMouseEventHandler): void; 24 | _forEachManager(handler: (commander: BaseCommander | BaseCommander) => any): void; 25 | _render(): void; 26 | } 27 | export {}; 28 | -------------------------------------------------------------------------------- /example/webpack.prod.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 3 | 4 | module.exports = { 5 | mode: 'development', 6 | entry: { 7 | 'canvas': path.resolve(__dirname, 'src', 'canvas', 'index.js'), 8 | 'css3': path.resolve(__dirname, 'src', 'css3', 'index.js'), 9 | 'index': path.resolve(__dirname, 'src', 'index.js'), 10 | }, 11 | output: { 12 | path: path.resolve(__dirname), 13 | filename: '[name].bundle.js' 14 | }, 15 | devServer: { 16 | port: 9527, 17 | host: 'localhost', 18 | hot: true 19 | }, 20 | module: { 21 | rules: [ 22 | { 23 | test: /\.m?js$/, 24 | exclude: /(node_modules|bower_components)/, 25 | use: { 26 | loader: 'babel-loader', 27 | options: { 28 | presets: ['@babel/preset-env'] 29 | } 30 | } 31 | } 32 | ] 33 | }, 34 | plugins: [ 35 | new HtmlWebpackPlugin({ 36 | filename: 'index.html', 37 | template: path.resolve(__dirname, 'src', 'index.html'), 38 | chunks: ['index'] 39 | }), 40 | new HtmlWebpackPlugin({ 41 | filename: 'canvas.html', 42 | template: path.resolve(__dirname, 'src', 'canvas','index.html'), 43 | chunks: ['canvas'] 44 | }), 45 | new HtmlWebpackPlugin({ 46 | filename: 'css3.html', 47 | template: path.resolve(__dirname, 'src', 'css3', 'index.html'), 48 | chunks: ['css3'] 49 | }) 50 | ] 51 | } -------------------------------------------------------------------------------- /example/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 3 | 4 | module.exports = { 5 | mode: 'development', 6 | entry: { 7 | 'canvas': path.resolve(__dirname, 'src', 'canvas', 'index.js'), 8 | 'css3': path.resolve(__dirname, 'src', 'css3', 'index.js'), 9 | 'index': path.resolve(__dirname, 'src', 'index.js'), 10 | }, 11 | output: { 12 | path: path.resolve(__dirname), 13 | filename: '[name].bundle.js' 14 | }, 15 | devServer: { 16 | port: 9527, 17 | host: 'localhost', 18 | hot: true 19 | }, 20 | module: { 21 | rules: [ 22 | { 23 | test: /\.m?js$/, 24 | exclude: /(node_modules|bower_components)/, 25 | use: { 26 | loader: 'babel-loader', 27 | options: { 28 | presets: ['@babel/preset-env'] 29 | } 30 | } 31 | } 32 | ] 33 | }, 34 | plugins: [ 35 | new HtmlWebpackPlugin({ 36 | filename: 'index.html', 37 | template: path.resolve(__dirname, 'src', 'index.html'), 38 | chunks: ['index'] 39 | }), 40 | new HtmlWebpackPlugin({ 41 | filename: 'canvas.html', 42 | template: path.resolve(__dirname, 'src', 'canvas','index.html'), 43 | chunks: ['canvas'] 44 | }), 45 | new HtmlWebpackPlugin({ 46 | filename: 'css3.html', 47 | template: path.resolve(__dirname, 'src', 'css3', 'index.html'), 48 | chunks: ['css3'] 49 | }) 50 | ] 51 | } -------------------------------------------------------------------------------- /src/commander/canvas/base-fixed.ts: -------------------------------------------------------------------------------- 1 | import BaseCanvasCommander from './base-canvas' 2 | import { FixedBarrageObejct, CommanderConfig } from '../../types' 3 | import { isEmptyArray } from '../../helper' 4 | 5 | export default abstract class BaseFixedCommander extends BaseCanvasCommander { 6 | constructor(canvas: HTMLCanvasElement, config: CommanderConfig) { 7 | super(canvas, config) 8 | } 9 | 10 | add(barrage: FixedBarrageObejct): boolean { 11 | const trackId = this._findTrack() 12 | if (trackId === -1) { 13 | return false 14 | } 15 | 16 | const track = this.tracks[trackId] 17 | const trackWidth = this.trackWidth 18 | const { width } = barrage 19 | const barrageOffset = (trackWidth - width) / 2 20 | const normalizedBarrage = Object.assign({}, barrage, { 21 | offset: barrageOffset, 22 | duration: this.duration 23 | }) 24 | track.push(normalizedBarrage) 25 | return true 26 | } 27 | 28 | _findTrack(): number { 29 | let idx = -1 30 | for (let i = 0; i < this.tracks.length; ++i) { 31 | if (isEmptyArray(this.tracks[i].barrages)) { 32 | idx = i 33 | break 34 | } 35 | } 36 | return idx 37 | } 38 | 39 | _extractBarrage(): void { 40 | let isIntered: boolean 41 | for (let i = 0; i < this.waitingQueue.length; ) { 42 | isIntered = this.add(this.waitingQueue[i]) 43 | if (!isIntered) { 44 | break 45 | } 46 | this.waitingQueue.shift() 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/event-emitter.ts: -------------------------------------------------------------------------------- 1 | interface EventMap { 2 | [x: string]: Array 3 | } 4 | 5 | interface EventHandler { 6 | (...args: any[]): any 7 | } 8 | 9 | export default class EventEmitter { 10 | private _eventsMap: EventMap = {} 11 | 12 | $on(eventName: string, handler: EventHandler) { 13 | const eventsMap = this._eventsMap 14 | const handlers = eventsMap[eventName] || (eventsMap[eventName] = []) 15 | handlers.push(handler) 16 | return this 17 | } 18 | 19 | $once(eventName: string, handler: EventHandler) { 20 | const eventsMap = this._eventsMap 21 | const handlers = eventsMap[eventName] || (eventsMap[eventName] = []) 22 | const self = this 23 | const fn = function(...args: any[]) { 24 | handler(...args) 25 | self.$off(eventName, fn) 26 | } 27 | handlers.push(fn) 28 | return this 29 | } 30 | 31 | $off(eventName: string, handler?: EventHandler) { 32 | const eventsMap = this._eventsMap 33 | if (!handler) { 34 | eventsMap[eventName].length = 0 35 | return this 36 | } 37 | 38 | const handlers = eventsMap[eventName] 39 | if (!handlers) { 40 | return this 41 | } 42 | 43 | const index = handlers.indexOf(handler) 44 | if (index !== -1) { 45 | handlers.splice(index, 1) 46 | } 47 | 48 | return this 49 | } 50 | 51 | $emit(eventName: string, ...args: any[]) { 52 | const eventsMap = this._eventsMap 53 | const handlers = eventsMap[eventName] 54 | if (Array.isArray(handlers)) { 55 | handlers.forEach(fn => fn(...args)) 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/event/index.ts: -------------------------------------------------------------------------------- 1 | import BarrageMaker from '../a-barrage' 2 | import { HTML_ELEMENT_NATIVE_EVENTS } from '../constants' 3 | 4 | export function injectNativeEvents(instance: BarrageMaker): void { 5 | HTML_ELEMENT_NATIVE_EVENTS.map(eventName => { 6 | instance.el.addEventListener(eventName, event => { 7 | instance.$emit(eventName, event) 8 | }) 9 | }) 10 | } 11 | 12 | export function injectEventsDelegator(instance: BarrageMaker): void { 13 | const proxyObject = instance.config.proxyObject 14 | if (!(proxyObject instanceof HTMLElement)) { 15 | return 16 | } 17 | type MouseEventName = 18 | | 'click' 19 | | 'dblclick' 20 | | 'mousedown' 21 | | 'mousemove' 22 | | 'mouseout' 23 | | 'mouseover' 24 | | 'mouseup' 25 | HTML_ELEMENT_NATIVE_EVENTS.map(eventName => { 26 | // ! 如果是联合类型 HtmlDivElement | HtmlCanvasElement 的话第二个参数会报错 27 | // ! 所以这里先用类型断言搞一搞 28 | ;(instance.el as HTMLElement).addEventListener(eventName as MouseEventName, (e: MouseEvent) => { 29 | const target = e.target 30 | if (target !== instance.el) { 31 | return 32 | } 33 | const event = new MouseEvent(eventName, { 34 | view: window, 35 | relatedTarget: proxyObject, 36 | altKey: e.altKey, 37 | button: e.button, 38 | buttons: e.buttons, 39 | clientX: e.clientX, 40 | clientY: e.clientY, 41 | ctrlKey: e.ctrlKey, 42 | metaKey: e.metaKey, 43 | movementX: e.movementX, 44 | movementY: e.movementY, 45 | screenX: e.screenX, 46 | screenY: e.screenY, 47 | shiftKey: e.shiftKey 48 | }) 49 | proxyObject.dispatchEvent(event) 50 | }) 51 | }) 52 | } 53 | -------------------------------------------------------------------------------- /src/commander/base.ts: -------------------------------------------------------------------------------- 1 | import { BarrageObject, CommanderConfig } from '../types' 2 | import Track from '../track' 3 | import EventEmitter from '../event-emitter' 4 | 5 | interface CommanderForEachHandler { 6 | (track: Track, index: number, array: Track[]): void 7 | } 8 | 9 | export default abstract class BaseCommander extends EventEmitter { 10 | protected trackWidth: number 11 | protected trackHeight: number 12 | protected duration: number 13 | protected maxTrack: number 14 | protected tracks: Track[] = [] 15 | protected poolSize: number 16 | waitingQueue: T[] = [] 17 | 18 | constructor(config: CommanderConfig) { 19 | super() 20 | this.trackWidth = config.trackWidth 21 | this.trackHeight = config.trackHeight 22 | this.duration = config.duration 23 | this.maxTrack = config.maxTrack 24 | this.poolSize = config.poolSize 25 | 26 | for (let i = 0; i < config.maxTrack; ++i) { 27 | this.tracks[i] = new Track() 28 | } 29 | } 30 | 31 | forEach(handler: CommanderForEachHandler) { 32 | for (let i = 0; i < this.tracks.length; ++i) { 33 | handler(this.tracks[i], i, this.tracks) 34 | } 35 | } 36 | 37 | // reset() { 38 | // this.forEach(track => track.reset()) 39 | // } 40 | 41 | resize(width?: number, height?: number) { 42 | if (width) { 43 | this.trackWidth = width 44 | } 45 | if (height) { 46 | this.trackHeight = height 47 | } 48 | } 49 | 50 | // 添加弹幕到等待队列 51 | abstract add(barrage: T): boolean 52 | // 寻找合适的轨道 53 | abstract _findTrack(): number 54 | // 从等待队列中抽取弹幕并放入弹幕 55 | abstract _extractBarrage(): void 56 | // 渲染函数 57 | abstract render(): void 58 | // 清空 59 | abstract reset(): void 60 | } 61 | -------------------------------------------------------------------------------- /tools/semantic-release-prepare.ts: -------------------------------------------------------------------------------- 1 | const path = require("path") 2 | const { fork } = require("child_process") 3 | const colors = require("colors") 4 | 5 | const { readFileSync, writeFileSync } = require("fs") 6 | const pkg = JSON.parse( 7 | readFileSync(path.resolve(__dirname, "..", "package.json")) 8 | ) 9 | 10 | pkg.scripts.prepush = "npm run test:prod && npm run build" 11 | pkg.scripts.commitmsg = "commitlint -E HUSKY_GIT_PARAMS" 12 | 13 | writeFileSync( 14 | path.resolve(__dirname, "..", "package.json"), 15 | JSON.stringify(pkg, null, 2) 16 | ) 17 | 18 | // Call husky to set up the hooks 19 | fork(path.resolve(__dirname, "..", "node_modules", "husky", "lib", "installer", 'bin'), ['install']) 20 | 21 | console.log() 22 | console.log(colors.green("Done!!")) 23 | console.log() 24 | 25 | if (pkg.repository.url.trim()) { 26 | console.log(colors.cyan("Now run:")) 27 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 28 | console.log(colors.cyan(" semantic-release-cli setup")) 29 | console.log() 30 | console.log( 31 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 32 | ) 33 | console.log() 34 | console.log( 35 | colors.gray( 36 | 'Note: Make sure "repository.url" in your package.json is correct before' 37 | ) 38 | ) 39 | } else { 40 | console.log( 41 | colors.red( 42 | 'First you need to set the "repository.url" property in package.json' 43 | ) 44 | ) 45 | console.log(colors.cyan("Then run:")) 46 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 47 | console.log(colors.cyan(" semantic-release-cli setup")) 48 | console.log() 49 | console.log( 50 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 51 | ) 52 | } 53 | 54 | console.log() 55 | -------------------------------------------------------------------------------- /src/stragy/canvas.ts: -------------------------------------------------------------------------------- 1 | import BarrageMaker from '../a-barrage' 2 | import { 3 | RawBarrageObject, 4 | CommanderMapKey, 5 | ScrollBarrageObject, 6 | FixedBarrageObejct 7 | } from '../types' 8 | 9 | export default { 10 | clear(this: BarrageMaker) { 11 | const { width, height } = this.canvas! 12 | this._forEachManager(manager => manager.reset()) 13 | this.ctx!.clearRect(0, 0, width, height) 14 | }, 15 | add(this: BarrageMaker, barrage: RawBarrageObject, type: CommanderMapKey = 'scroll') { 16 | const { text, color, size } = barrage 17 | const ctx = this.ctx! 18 | const fontSize = (size || this.config.fontSize) * this.config.zoom 19 | const fontColor = color || this.config.fontColor 20 | 21 | ctx.font = `${fontSize}px 'Microsoft Yahei'` 22 | const { width } = ctx.measureText(text) 23 | if (type === 'scroll') { 24 | const barrageObject: ScrollBarrageObject = { 25 | text, 26 | width, 27 | color: fontColor, 28 | size: fontSize, 29 | speed: 0, 30 | offset: 0 31 | } 32 | this.commanderMap[type].waitingQueue.push(barrageObject) 33 | } else { 34 | const barrageObject: FixedBarrageObejct = { 35 | text, 36 | width, 37 | color: fontColor, 38 | size: fontSize, 39 | duration: 0, 40 | offset: 0 41 | } 42 | this.commanderMap[type].waitingQueue.push(barrageObject) 43 | } 44 | }, 45 | _render(this: BarrageMaker) { 46 | const ctx = this.ctx! 47 | const canvas = this.canvas! 48 | ctx.shadowBlur = 2 49 | ctx.shadowColor = 'rgba(0, 0, 0, 0.8)' 50 | ctx.clearRect(0, 0, canvas.width, canvas.height) 51 | this._forEachManager(manager => manager.render()) 52 | 53 | this.animation = requestAnimationFrame(this._render.bind(this)) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /test/event-emitter.spec.ts: -------------------------------------------------------------------------------- 1 | import EventEmitter from '../src/event-emitter' 2 | 3 | describe('event-emitter', () => { 4 | test('$on', () => { 5 | const emt = new EventEmitter() 6 | const EVENT_1 = 'event1' 7 | const EVENT_2 = 'event2' 8 | const fn1 = jest.fn(() => {}) 9 | const fn2 = jest.fn(() => {}) 10 | emt.$on(EVENT_1, fn1) 11 | emt.$on(EVENT_1, fn2) 12 | emt.$on(EVENT_2, fn1) 13 | emt.$emit(EVENT_1) 14 | emt.$emit(EVENT_2) 15 | emt.$emit(EVENT_1) 16 | expect(fn1.mock.calls.length).toBe(3) 17 | expect(fn2.mock.calls.length).toBe(2) 18 | }) 19 | 20 | test('$once', () => { 21 | const emt = new EventEmitter() 22 | const EVENT_1 = 'event1' 23 | const fn1 = jest.fn(() => {}) 24 | emt.$once(EVENT_1, fn1) 25 | emt.$emit(EVENT_1) 26 | emt.$emit(EVENT_1) 27 | expect(fn1.mock.calls.length).toBe(1) 28 | }) 29 | 30 | test('$off', () => { 31 | const emt = new EventEmitter() 32 | const EVENT_1 = 'event1' 33 | const EVENT_2 = 'event2' 34 | const fn1 = jest.fn(() => {}) 35 | const fn2 = jest.fn(() => {}) 36 | emt.$on(EVENT_1, fn1) 37 | emt.$on(EVENT_1, fn2) 38 | emt.$on(EVENT_2, fn1) 39 | emt.$on(EVENT_2, fn2) 40 | emt.$off(EVENT_2) 41 | emt.$off(EVENT_1, fn1) 42 | emt.$off('dasa', fn1) 43 | emt.$emit(EVENT_1) 44 | emt.$emit(EVENT_2) 45 | expect(fn1.mock.calls.length).toBe(0) 46 | expect(fn2.mock.calls.length).toBe(1) 47 | }) 48 | 49 | test('$emit', () => { 50 | const emt = new EventEmitter() 51 | const EVENT_1 = 'event1' 52 | const fn1 = jest.fn(() => {}) 53 | const fn2 = jest.fn(() => {}) 54 | emt.$on(EVENT_1, fn1).$on(EVENT_1, fn2) 55 | emt.$emit(EVENT_1) 56 | expect(fn1.mock.calls.length).toBe(1) 57 | expect(fn1.mock.calls.length).toBe(1) 58 | }) 59 | }) 60 | -------------------------------------------------------------------------------- /dist/types/types/index.d.ts: -------------------------------------------------------------------------------- 1 | import BaseCommander from '../commander/base'; 2 | export interface BarrageConfig { 3 | engine: 'canvas' | 'css3'; 4 | zoom: number; 5 | proxyObject: HTMLElement | null; 6 | usePointerEvents: boolean; 7 | maxTrack: number; 8 | fontSize: number; 9 | fontColor: string; 10 | duration: number; 11 | trackHeight: number; 12 | wrapper: HTMLElement | null; 13 | } 14 | export interface RawBarrageObject { 15 | text: string; 16 | color?: string; 17 | size?: number; 18 | } 19 | export interface BarrageObject { 20 | text: string; 21 | color: string; 22 | size: number; 23 | width: number; 24 | offset: number; 25 | freeze?: boolean; 26 | } 27 | export interface ScrollBarrageObject extends BarrageObject { 28 | speed: number; 29 | } 30 | export interface FixedBarrageObejct extends BarrageObject { 31 | duration: number; 32 | } 33 | export interface CommanderMap { 34 | scroll: BaseCommander; 35 | 'fixed-top': BaseCommander; 36 | 'fixed-bottom': BaseCommander; 37 | } 38 | export declare type CommanderMapKey = keyof CommanderMap; 39 | export interface CommanderConfig { 40 | trackWidth: number; 41 | trackHeight: number; 42 | duration: number; 43 | maxTrack: number; 44 | wrapper?: HTMLElement; 45 | } 46 | export interface RollingRenderCommanderContructor { 47 | new (...args: any[]): BaseCommander; 48 | } 49 | export interface FixedRenderCommanderContructor { 50 | new (...args: any[]): BaseCommander; 51 | } 52 | export interface RenderEngine { 53 | FixedTopCommander: FixedRenderCommanderContructor; 54 | FixedBottomCommander: FixedRenderCommanderContructor; 55 | RollingCommander: RollingRenderCommanderContructor; 56 | } 57 | export interface BarrageMouseEventHandler { 58 | (barrage: BarrageObject, el: HTMLElement): void; 59 | } 60 | -------------------------------------------------------------------------------- /src/stragy/css3.ts: -------------------------------------------------------------------------------- 1 | import BarrageMaker from '../a-barrage' 2 | import { 3 | RawBarrageObject, 4 | CommanderMapKey, 5 | ScrollBarrageObject, 6 | FixedBarrageObejct 7 | } from '../types' 8 | // import { createBarrage, appendChild } from '../helper/css'; 9 | // import RollingCssCommander from '../commander/css-renderer/rolling'; 10 | import { requestAnimationFrame } from '../helper' 11 | 12 | export default { 13 | clear(this: BarrageMaker) { 14 | this._forEachManager(manager => manager.reset()) 15 | }, 16 | add(this: BarrageMaker, barrage: RawBarrageObject, type: CommanderMapKey = 'scroll') { 17 | const { text, color = this.config.fontColor, size = this.config.fontSize } = barrage 18 | const fontColor = color 19 | const fontSize = size * this.config.zoom 20 | const trackWidth = this.el.offsetWidth 21 | // const posLeft = trackWidth + 'px'; 22 | 23 | // const danmu = createBarrage(text, fontColor, fontSize, posLeft); 24 | // appendChild(this.el, danmu); 25 | // const width = danmu.offsetWidth; 26 | if (type === 'scroll') { 27 | const barrageObject: ScrollBarrageObject = { 28 | text, 29 | width: 0, 30 | color: fontColor, 31 | size: fontSize, 32 | speed: 0, 33 | offset: trackWidth 34 | } 35 | // (this.commanderMap[type] as RollingCssCommander).objToElm.set(barrageObject, danmu); 36 | this.commanderMap[type].waitingQueue.push(barrageObject) 37 | } else { 38 | const barrageObject: FixedBarrageObejct = { 39 | text, 40 | width: 0, 41 | color: fontColor, 42 | size: fontSize, 43 | duration: this.config.duration, 44 | offset: trackWidth 45 | } 46 | this.commanderMap[type].waitingQueue.push(barrageObject) 47 | } 48 | }, 49 | _render(this: BarrageMaker) { 50 | this._forEachManager(manager => manager.render()) 51 | 52 | this.animation = requestAnimationFrame(this._render.bind(this)) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- 1 | import BaseCommander from '../commander/base' 2 | 3 | export interface BarrageConfig { 4 | engine: 'canvas' | 'css3' 5 | zoom: number 6 | proxyObject: HTMLElement | undefined 7 | usePointerEvents: boolean 8 | maxTrack: number 9 | fontSize: number 10 | fontColor: string 11 | duration: number 12 | trackHeight: number 13 | wrapper: HTMLElement | undefined 14 | interactive: boolean 15 | poolSize: number 16 | } 17 | 18 | export interface RawBarrageObject { 19 | text: string 20 | color?: string 21 | size?: number 22 | } 23 | 24 | export interface BarrageObject { 25 | text: string 26 | color: string 27 | size: number 28 | width: number 29 | offset: number 30 | freeze?: boolean 31 | } 32 | 33 | export interface ScrollBarrageObject extends BarrageObject { 34 | speed: number 35 | } 36 | 37 | export interface FixedBarrageObejct extends BarrageObject { 38 | duration: number 39 | } 40 | 41 | export interface CommanderMap { 42 | scroll: BaseCommander 43 | 'fixed-top': BaseCommander 44 | 'fixed-bottom': BaseCommander 45 | } 46 | 47 | export type CommanderMapKey = keyof CommanderMap 48 | 49 | export interface CommanderConfig { 50 | trackWidth: number 51 | trackHeight: number 52 | duration: number 53 | maxTrack: number 54 | wrapper?: HTMLElement 55 | interactive: boolean 56 | poolSize: number 57 | } 58 | 59 | export interface RollingRenderCommanderContructor { 60 | new (...args: any[]): BaseCommander 61 | } 62 | 63 | export interface FixedRenderCommanderContructor { 64 | new (...args: any[]): BaseCommander 65 | } 66 | 67 | export interface RenderEngine { 68 | FixedTopCommander: FixedRenderCommanderContructor 69 | FixedBottomCommander: FixedRenderCommanderContructor 70 | RollingCommander: RollingRenderCommanderContructor 71 | } 72 | 73 | export interface BarrageMouseEventHandler { 74 | (barrage: BarrageObject, el: HTMLElement): void 75 | } 76 | -------------------------------------------------------------------------------- /example/src/css3/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ABarrage Demo Page 8 | 9 | 10 | 11 | 12 | 13 |
14 |
15 | 24 |
25 |
26 |
27 |
28 | 输入弹幕: 29 | 30 | 发送滚动弹幕 31 | 发送顶部弹幕 32 | 发送底部弹幕 33 |
34 |
35 | 弹幕不透明度: 36 | 37 |
38 |
39 |
40 | 41 | 42 | -------------------------------------------------------------------------------- /example/src/canvas/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ABarrage Demo Page 8 | 9 | 10 | 11 | 12 | 13 |
14 |
15 | 24 | 25 |
26 |
27 |
28 | 输入弹幕: 29 | 30 | 发送滚动弹幕 31 | 发送顶部弹幕 32 | 发送底部弹幕 33 |
34 |
35 | 弹幕不透明度: 36 | 37 |
38 |
39 |
40 | 41 | 42 | -------------------------------------------------------------------------------- /example/css3.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ABarrage Demo Page 8 | 9 | 10 | 11 | 12 | 13 |
14 |
15 | 24 |
25 |
26 |
27 |
28 | 输入弹幕: 29 | 30 | 发送滚动弹幕 31 | 发送顶部弹幕 32 | 发送底部弹幕 33 |
34 |
35 | 弹幕不透明度: 36 | 37 |
38 |
39 |
40 | 41 | 42 | -------------------------------------------------------------------------------- /example/canvas.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ABarrage Demo Page 8 | 9 | 10 | 11 | 12 | 13 |
14 |
15 | 24 | 25 |
26 |
27 |
28 | 输入弹幕: 29 | 30 | 发送滚动弹幕 31 | 发送顶部弹幕 32 | 发送底部弹幕 33 |
34 |
35 | 弹幕不透明度: 36 | 37 |
38 |
39 |
40 | 41 | 42 | -------------------------------------------------------------------------------- /src/commander/css-renderer/base-fixed.ts: -------------------------------------------------------------------------------- 1 | import BaseCssCommander from './base-css' 2 | import { CommanderConfig, FixedBarrageObejct } from '../../types' 3 | import Track from '../../track' 4 | import { isEmptyArray } from '../../helper' 5 | import { createBarrage, appendChild } from '../../helper/css' 6 | 7 | export default abstract class BaseFixedCssCommander extends BaseCssCommander { 8 | protected elHeight: number 9 | 10 | constructor(el: HTMLDivElement, config: CommanderConfig) { 11 | super(el, config) 12 | 13 | this.elHeight = el.offsetHeight 14 | } 15 | 16 | add(barrage: FixedBarrageObejct): boolean { 17 | const trackId = this._findTrack() 18 | if (trackId === -1) { 19 | return false 20 | } 21 | // 创建弹幕DOM 22 | const { text, size, color, offset } = barrage 23 | const fontSize = size + 'px' 24 | let posLeft = offset + 'px' 25 | const danmu = createBarrage(text, color, fontSize, posLeft) 26 | appendChild(this.el, danmu) 27 | const width = danmu.offsetWidth 28 | 29 | // 计算位置 30 | const track = this.tracks[trackId] 31 | const trackWidth = this.trackWidth 32 | const barrageOffset = (trackWidth - width) / 2 33 | const normalizedBarrage = Object.assign({}, barrage, { 34 | offset: barrageOffset, 35 | duration: this.duration, 36 | width 37 | }) 38 | 39 | this.objToElm.set(normalizedBarrage, danmu) 40 | this.elmToObj.set(danmu, normalizedBarrage) 41 | track.push(normalizedBarrage) 42 | return true 43 | } 44 | 45 | _findTrack(): number { 46 | let idx = -1 47 | for (let i = 0; i < this.tracks.length; ++i) { 48 | if (isEmptyArray(this.tracks[i].barrages)) { 49 | idx = i 50 | break 51 | } 52 | } 53 | return idx 54 | } 55 | 56 | _extractBarrage(): void { 57 | let isIntered: boolean 58 | for (let i = 0; i < this.waitingQueue.length; ) { 59 | isIntered = this.add(this.waitingQueue[i]) 60 | if (!isIntered) { 61 | break 62 | } 63 | this.waitingQueue.shift() 64 | } 65 | } 66 | 67 | _removeTopElementFromTrack(track: Track) { 68 | const barrage = track.barrages[0] 69 | if (!barrage) { 70 | return 71 | } 72 | const el = this.objToElm.get(barrage)! 73 | this.objToElm.delete(barrage) 74 | this.elmToObj.delete(el) 75 | this.removeElement(el) 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /example/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ABarrage 高性能JavaScript弹幕库 8 | 9 | 10 | 11 | 98 | 99 | 100 |
101 | 102 |
103 | 107 | 114 |
115 | View on Github 116 |
117 |
118 |
119 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ABarrage 高性能JavaScript弹幕库 8 | 9 | 10 | 11 | 98 | 99 | 100 |
101 | 102 |
103 | 107 | 114 |
115 | View on Github 116 |
117 |
118 |
119 | -------------------------------------------------------------------------------- /src/commander/css-renderer/base-css.ts: -------------------------------------------------------------------------------- 1 | import BaseCommander from '../base' 2 | import { BarrageObject, CommanderConfig } from '../../types' 3 | import { setHoverStyle, setBlurStyle, createBarrage as _createBarrage } from '../../helper/css' 4 | export default abstract class BaseCssCommander extends BaseCommander { 5 | el: HTMLDivElement 6 | objToElm: WeakMap = new WeakMap() 7 | elmToObj: WeakMap = new WeakMap() 8 | freezeBarrage: T | null = null 9 | domPool: Array = [] 10 | 11 | constructor(el: HTMLDivElement, config: CommanderConfig) { 12 | super(config) 13 | 14 | this.el = el 15 | 16 | const wrapper = config.wrapper 17 | if (wrapper && config.interactive) { 18 | wrapper.addEventListener('mousemove', this._mouseMoveEventHandler.bind(this)) 19 | wrapper.addEventListener('click', this._mouseClickEventHandler.bind(this)) 20 | } 21 | } 22 | 23 | createBarrage(text: string, color: string, fontSize: string, left: string) { 24 | if (this.domPool.length) { 25 | const el = this.domPool.pop() 26 | return _createBarrage(text, color, fontSize, left, el) 27 | } else { 28 | return _createBarrage(text, color, fontSize, left) 29 | } 30 | } 31 | 32 | removeElement(target: HTMLElement) { 33 | if (this.domPool.length < this.poolSize) { 34 | this.domPool.push(target) 35 | return 36 | } 37 | this.el.removeChild(target) 38 | } 39 | 40 | _mouseMoveEventHandler(e: Event) { 41 | const target = e.target 42 | if (!target) { 43 | return 44 | } 45 | 46 | const newFreezeBarrage = this.elmToObj.get(target as HTMLElement) 47 | const oldFreezeBarrage = this.freezeBarrage 48 | 49 | if (newFreezeBarrage === oldFreezeBarrage) { 50 | return 51 | } 52 | 53 | this.freezeBarrage = null 54 | 55 | if (newFreezeBarrage) { 56 | this.freezeBarrage = newFreezeBarrage 57 | newFreezeBarrage.freeze = true 58 | setHoverStyle(target as HTMLElement) 59 | this.$emit('hover', newFreezeBarrage, target as HTMLElement) 60 | } 61 | 62 | if (oldFreezeBarrage) { 63 | oldFreezeBarrage.freeze = false 64 | const oldFreezeElm = this.objToElm.get(oldFreezeBarrage) 65 | oldFreezeElm && setBlurStyle(oldFreezeElm) 66 | this.$emit('blur', oldFreezeBarrage, oldFreezeElm) 67 | } 68 | } 69 | 70 | _mouseClickEventHandler(e: Event) { 71 | const target = e.target 72 | const barrageObject = this.elmToObj.get(target as HTMLElement) 73 | if (barrageObject) { 74 | this.$emit('click', barrageObject, target) 75 | } 76 | } 77 | 78 | reset() { 79 | this.forEach(track => { 80 | track.forEach(barrage => { 81 | const el = this.objToElm.get(barrage) 82 | if (!el) { 83 | return 84 | } 85 | this.removeElement(el) 86 | }) 87 | track.reset() 88 | }) 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/helper/index.ts: -------------------------------------------------------------------------------- 1 | import { ScrollBarrageObject, FixedBarrageObejct } from '../types' 2 | 3 | export function isEmptyArray(array: T[]): boolean { 4 | return array.length === 0 5 | } 6 | 7 | export function getArrayRight(array: T[]): T { 8 | return array[array.length - 1] 9 | } 10 | 11 | export function isDiv(el: any): el is HTMLDivElement { 12 | return el instanceof HTMLDivElement 13 | } 14 | 15 | export function isCanvas(el: any): el is HTMLCanvasElement { 16 | return el instanceof HTMLCanvasElement 17 | } 18 | 19 | export function getEl( 20 | el: HTMLDivElement | HTMLCanvasElement | string, 21 | type: 'css3' | 'canvas' 22 | ): HTMLDivElement | HTMLCanvasElement { 23 | const $ = document.querySelector 24 | let _el = typeof el === 'string' ? $(el) : el 25 | if (type === 'canvas' && !isCanvas(_el)) { 26 | throwElError('canvas') 27 | } 28 | if (type === 'css3' && !isDiv(_el)) { 29 | throwElError('css3') 30 | } 31 | 32 | return _el as HTMLCanvasElement | HTMLDivElement 33 | 34 | function throwElError(type: 'canvas' | 'css3'): never { 35 | const EL_TYPE = type === 'canvas' ? 'HTMLCanvasElement' : 'HTMLDivElement' 36 | throw new Error(`Engine Error: el is not a ${EL_TYPE} instance.(engine: ${type})`) 37 | } 38 | } 39 | 40 | export const requestAnimationFrame = 41 | window.requestAnimationFrame || window.webkitRequestAnimationFrame 42 | 43 | export const cancelAnimationFrame = window.cancelAnimationFrame || window.webkitCancelAnimationFrame 44 | 45 | export const isFunction = function(fn: any): fn is Function { 46 | return typeof fn === 'function' 47 | } 48 | 49 | export const isNull = function(o: any): o is null { 50 | return o === null 51 | } 52 | 53 | export const isUndefined = function(o: any): o is undefined { 54 | return typeof o === 'undefined' 55 | } 56 | 57 | export const isObject = function(o: any): o is object { 58 | return typeof o === 'object' && o !== null 59 | } 60 | 61 | export const isPlainObject = function(o: any): o is object { 62 | return Object.prototype.toString.call(o) === '[object Object]' 63 | } 64 | 65 | export function deepMerge(...objects: any[]): any { 66 | const ret: any = {} 67 | objects.forEach(obj => { 68 | if (isNull(obj) || isUndefined(obj)) { 69 | return 70 | } 71 | Object.keys(obj).forEach((key: string) => { 72 | if (!ret.hasOwnProperty(key)) { 73 | ret[key] = obj[key] 74 | } else { 75 | if (Array.isArray(obj[key])) { 76 | ret[key] = obj[key] 77 | } else if (isPlainObject(obj[key])) { 78 | ret[key] = deepMerge(ret[key], obj[key]) 79 | } else { 80 | ret[key] = obj[key] 81 | } 82 | } 83 | }) 84 | }) 85 | return ret 86 | } 87 | 88 | export function isScrollBarrage(x: any): x is ScrollBarrageObject { 89 | return x.hasOwnProperty('speed') && x.hasOwnProperty('offset') 90 | } 91 | 92 | export function isFixedBarrage(x: any): x is FixedBarrageObejct { 93 | return x.hasOwnProperty('duration') 94 | } 95 | -------------------------------------------------------------------------------- /src/commander/canvas/rolling.ts: -------------------------------------------------------------------------------- 1 | import BaseCanvasCommander from './base-canvas' 2 | import { ScrollBarrageObject, CommanderConfig } from '../../types' 3 | import { isEmptyArray, getArrayRight } from '../../helper' 4 | import { TIME_PER_FRAME } from '../../constants' 5 | import Track from '../../track' 6 | 7 | export default class RollingCommander extends BaseCanvasCommander { 8 | constructor(canvas: HTMLCanvasElement, config: CommanderConfig) { 9 | super(canvas, config) 10 | } 11 | 12 | private get _defaultSpeed(): number { 13 | return (this.trackWidth / this.duration) * TIME_PER_FRAME 14 | } 15 | 16 | private get _randomSpeed(): number { 17 | return 0.8 + Math.random() * 1.3 18 | } 19 | 20 | add(barrage: ScrollBarrageObject): boolean { 21 | const trackId = this._findTrack() 22 | if (trackId === -1) { 23 | return false 24 | } 25 | 26 | const track = this.tracks[trackId] 27 | const trackOffset = track.offset 28 | const trackWidth = this.trackWidth 29 | let speed: number 30 | if (isEmptyArray(track.barrages)) { 31 | speed = this._defaultSpeed * this._randomSpeed 32 | } else { 33 | const { speed: preSpeed } = getArrayRight(track.barrages) 34 | speed = (trackWidth * preSpeed) / trackOffset 35 | } 36 | speed = Math.min(speed, this._defaultSpeed * 2) 37 | const normalizedBarrage = Object.assign({}, barrage, { 38 | offset: trackWidth, 39 | speed 40 | }) 41 | track.push(normalizedBarrage) 42 | track.offset = trackWidth + barrage.width * 1.2 43 | return true 44 | } 45 | 46 | _findTrack(): number { 47 | let idx = -1 48 | let max = -Infinity 49 | this.forEach((track, index) => { 50 | const trackOffset = track.offset 51 | if (trackOffset > this.trackWidth) { 52 | return 53 | } 54 | const t = this.trackWidth - trackOffset 55 | if (t > max) { 56 | idx = index 57 | max = t 58 | } 59 | }) 60 | return idx 61 | } 62 | 63 | _extractBarrage(): void { 64 | let isIntered: boolean 65 | for (let i = 0; i < this.waitingQueue.length; ) { 66 | isIntered = this.add(this.waitingQueue[i]) 67 | if (!isIntered) { 68 | break 69 | } 70 | this.waitingQueue.shift() 71 | } 72 | } 73 | 74 | render(): void { 75 | this._extractBarrage() 76 | const ctx = this.ctx 77 | const trackHeight = this.trackHeight 78 | this.forEach((track: Track, trackIndex) => { 79 | let removeTop = false 80 | track.forEach((barrage, barrageIndex) => { 81 | const { color, text, offset, speed, width, size } = barrage 82 | ctx.fillStyle = color 83 | ctx.font = `${size}px 'Microsoft Yahei'` 84 | ctx.fillText(text, offset, (trackIndex + 1) * trackHeight) 85 | barrage.offset -= speed 86 | if (barrageIndex === 0 && barrage.offset < 0 && Math.abs(barrage.offset) >= width) { 87 | removeTop = true 88 | } 89 | }) 90 | track.updateOffset() 91 | if (removeTop) { 92 | track.removeTop() 93 | } 94 | }) 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /example/src/canvas/index.js: -------------------------------------------------------------------------------- 1 | import Barrage from '../../../dist/barrage.umd'; 2 | import faker from 'faker/locale/zh_CN'; 3 | 4 | function mockBarrage() { 5 | return { 6 | text: faker.lorem.words(), 7 | color: '#fff' 8 | }; 9 | } 10 | 11 | const $ = (selector) => document.querySelector(selector); 12 | export const HTML_ELEMENT_NATIVE_EVENTS = 'click,dblclick,mousedown,mousemove,mouseout,mouseover,mouseup'.split(','); 13 | 14 | const player = $('#my-player'); 15 | const danmu = $('#danmu'); 16 | danmu.width = 960; 17 | danmu.height = 400; 18 | // const container = $('#container'); 19 | const barrage = new Barrage(danmu, { 20 | proxyObject: player, 21 | scroll: { 22 | fontSize: 28, 23 | duration: 5000 24 | }, 25 | engine: 'canvas', 26 | usePointerEvents: true, 27 | trackWidth: 960 28 | }); 29 | 30 | ['click'].forEach(eventName => { 31 | player.addEventListener(eventName, e => { 32 | console.log(`${eventName} call by player`, e); 33 | }); 34 | }); 35 | 36 | let timer= null; 37 | player.onpause = () => { 38 | console.log('pause'); 39 | clearTimeout(timer); 40 | barrage.stop(); 41 | }; 42 | player.onplay = () => { 43 | console.log('start'); 44 | barrage.start(); 45 | timer = setTimeout(function insertBarrage() { 46 | let sumScroll = 1 + Math.floor(5 * Math.random()); 47 | while(sumScroll--) { 48 | barrage.add(mockBarrage(), 'scroll'); 49 | } 50 | 51 | // let sumFixedTop = 10 + Math.floor(50 * Math.random()); 52 | // while(sumFixedTop--) { 53 | // barrage.add(mockBarrage(), 'fixed-top'); 54 | // } 55 | 56 | // let sumFixedBottom = 10 + Math.floor(50 * Math.random()); 57 | // while(sumFixedBottom--) { 58 | // barrage.add(mockBarrage(), 'fixed-bottom'); 59 | // } 60 | 61 | timer = setTimeout(insertBarrage, 2000 + Math.floor(Math.random() * 10000)); 62 | }, 2000); 63 | }; 64 | // player.onresize = () => { 65 | // console.log('onresize'); 66 | // resizeDanmu(); 67 | // }; 68 | player.onseeked = () => { 69 | barrage.clear(); 70 | }; 71 | 72 | // resizeDanmu(); 73 | 74 | function resizeDanmu() { 75 | const { width, height } = player.getBoundingClientRect(); 76 | danmu.width = width; 77 | danmu.height = height; 78 | danmu.style.width = width + 'px'; 79 | danmu.style.height = height + 'px'; 80 | barrage.resize(width); 81 | } 82 | 83 | new Vue({ 84 | el: '#dashboard', 85 | data() { 86 | return { 87 | barrageText: '哔哩哔哩干杯', 88 | opacity: 1, 89 | fontBase: 1 90 | } 91 | }, 92 | methods: { 93 | sendBarrage(type) { 94 | if (this.barrageText.trim() === '') { 95 | this.$notify.error({ 96 | title: '失败', 97 | message: '弹幕内容不能为空' 98 | }); 99 | return; 100 | } 101 | barrage.add({ 102 | text: this.barrageText 103 | }, type); 104 | this.barrageText = ''; 105 | this.$notify({ 106 | title: '成功', 107 | message: '弹幕发送成功', 108 | type: 'success' 109 | }); 110 | }, 111 | opacityChange(val) { 112 | barrage.setOpacity(val); 113 | }, 114 | fontSizeChange(val) { 115 | barrage.setFontSize(val); 116 | } 117 | } 118 | }); -------------------------------------------------------------------------------- /code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at alexjovermorales@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /example/src/css3/index.js: -------------------------------------------------------------------------------- 1 | import Barrage from '../../../dist/barrage.umd'; 2 | import faker from 'faker/locale/zh_CN'; 3 | 4 | function mockBarrage() { 5 | return { 6 | text: faker.lorem.words(), 7 | color: '#fff' 8 | }; 9 | } 10 | 11 | const $ = (selector) => document.querySelector(selector); 12 | export const HTML_ELEMENT_NATIVE_EVENTS = 'click,dblclick,mousedown,mousemove,mouseout,mouseover,mouseup'.split(','); 13 | 14 | const player = $('#my-player'); 15 | const danmu = $('#danmu'); 16 | const container = $('#container'); 17 | const barrage = new Barrage(danmu, { 18 | proxyObject: player, 19 | scroll: { 20 | fontSize: 28, 21 | duration: 5000 22 | }, 23 | engine: 'css3', 24 | usePointerEvents: true, 25 | wrapper: container, 26 | interactive: true, 27 | trackWidth: 960 28 | }); 29 | 30 | barrage.onBarrageBlur((barrage) => { 31 | console.log(`blur: ${barrage.text}`); 32 | }); 33 | 34 | barrage.onBarrageHover((barrage) => { 35 | console.log(`hover: ${barrage.text}`); 36 | }); 37 | 38 | barrage.onBarrageClick((barrage) => { 39 | console.log(`click: ${barrage.text}`); 40 | }); 41 | 42 | ['click'].forEach(eventName => { 43 | player.addEventListener(eventName, e => { 44 | console.log(`${eventName} call by player`, e); 45 | }); 46 | }); 47 | 48 | let timer= null; 49 | player.onpause = () => { 50 | console.log('pause'); 51 | clearTimeout(timer); 52 | barrage.stop(); 53 | }; 54 | player.onplay = () => { 55 | console.log('start'); 56 | barrage.start(); 57 | timer = setTimeout(function insertBarrage() { 58 | let sumScroll = 1 + Math.floor(5 * Math.random()); 59 | while(sumScroll--) { 60 | barrage.add(mockBarrage(), 'scroll'); 61 | } 62 | 63 | // let sumFixedTop = 10 + Math.floor(50 * Math.random()); 64 | // while(sumFixedTop--) { 65 | // barrage.add(mockBarrage(), 'fixed-top'); 66 | // } 67 | 68 | // let sumFixedBottom = 10 + Math.floor(50 * Math.random()); 69 | // while(sumFixedBottom--) { 70 | // barrage.add(mockBarrage(), 'fixed-bottom'); 71 | // } 72 | 73 | timer = setTimeout(insertBarrage, 2000 + Math.floor(Math.random() * 10000)); 74 | }, 2000); 75 | }; 76 | // player.onresize = () => { 77 | // console.log('onresize'); 78 | // resizeDanmu(); 79 | // }; 80 | player.onseeked = () => { 81 | barrage.clear(); 82 | }; 83 | 84 | // resizeDanmu(); 85 | 86 | // function resizeDanmu() { 87 | // const { width, height } = player.getBoundingClientRect(); 88 | // danmu.width = width; 89 | // danmu.height = height; 90 | // danmu.style.width = width + 'px'; 91 | // danmu.style.height = height + 'px'; 92 | // barrage.resize(width); 93 | // } 94 | 95 | new Vue({ 96 | el: '#dashboard', 97 | data() { 98 | return { 99 | barrageText: '哔哩哔哩干杯', 100 | opacity: 1, 101 | fontBase: 1 102 | } 103 | }, 104 | methods: { 105 | sendBarrage(type) { 106 | if (this.barrageText.trim() === '') { 107 | this.$notify.error({ 108 | title: '失败', 109 | message: '弹幕内容不能为空' 110 | }); 111 | return; 112 | } 113 | barrage.add({ 114 | text: this.barrageText 115 | }, type); 116 | this.barrageText = ''; 117 | this.$notify({ 118 | title: '成功', 119 | message: '弹幕发送成功', 120 | type: 'success' 121 | }); 122 | }, 123 | opacityChange(val) { 124 | barrage.setOpacity(val); 125 | }, 126 | fontSizeChange(val) { 127 | barrage.setFontSize(val); 128 | } 129 | } 130 | }); -------------------------------------------------------------------------------- /test/helpers/index.spec.ts: -------------------------------------------------------------------------------- 1 | import { 2 | isEmptyArray, 3 | getArrayRight, 4 | getEl, 5 | isFunction, 6 | isUndefined, 7 | isObject, 8 | deepMerge, 9 | isScrollBarrage, 10 | isFixedBarrage, 11 | requestAnimationFrame, 12 | cancelAnimationFrame 13 | } from '../../src/helper' 14 | 15 | describe('helpers test', () => { 16 | test('isEmptyArray', () => { 17 | const a: number[] = [] 18 | const b: number[] = [1] 19 | expect(isEmptyArray(a)).toBeTruthy() 20 | expect(isEmptyArray(b)).toBeFalsy() 21 | }) 22 | 23 | test('getArrayRight', () => { 24 | const a: number[] = [1, 2] 25 | const b: number[] = [] 26 | expect(getArrayRight(a)).toBe(2) 27 | expect(getArrayRight(b)).toBeUndefined() 28 | }) 29 | 30 | test('getEl', () => { 31 | const id = 'abcd' 32 | const el = document.createElement('div') 33 | el.id = id 34 | document.body.append(el) 35 | expect(getEl(`#${id}`)).toBe(el) 36 | expect(getEl(el)).toBe(el) 37 | expect(getEl('#aaa')).toBeNull() 38 | }) 39 | 40 | test('isFunction', () => { 41 | const fn = () => {} 42 | const fn2 = {} 43 | expect(isFunction(fn)).toBeTruthy() 44 | expect(isFunction(fn2)).toBeFalsy() 45 | }) 46 | 47 | test('isUndefined', () => { 48 | const a = undefined 49 | const b = {} 50 | const c = null 51 | expect(isUndefined(a)).toBeTruthy() 52 | expect(isUndefined(b)).toBeFalsy() 53 | expect(isUndefined(c)).toBeFalsy() 54 | }) 55 | 56 | test('isObject', () => { 57 | const a = {} 58 | const b = new Date() 59 | const c = null 60 | const d = 1 61 | expect(isObject(a)).toBeTruthy() 62 | expect(isObject(b)).toBeTruthy() 63 | expect(isObject(c)).toBeFalsy() 64 | expect(isObject(d)).toBeFalsy() 65 | }) 66 | 67 | test('deepMerge', () => { 68 | const obj1 = { 69 | a: 123, 70 | b: [1, 2, 3], 71 | c: { 72 | a: 1, 73 | b: 2, 74 | c: { 75 | a: 3, 76 | b: 4 77 | } 78 | }, 79 | d: null 80 | } 81 | const obj2 = { 82 | a: 456, 83 | b: [1], 84 | c: { 85 | d: 3 86 | }, 87 | f: undefined 88 | } 89 | const merged = deepMerge(obj1, obj2, undefined, null) 90 | expect(merged).toEqual({ 91 | a: 456, 92 | b: [1], 93 | c: { 94 | a: 1, 95 | b: 2, 96 | c: { 97 | a: 3, 98 | b: 4 99 | }, 100 | d: 3 101 | }, 102 | d: null, 103 | f: undefined 104 | }) 105 | const merged2 = deepMerge(null, undefined) 106 | expect(merged2).toEqual({}) 107 | }) 108 | 109 | test('isScrollBarrage', () => { 110 | const a = { 111 | speed: 21, 112 | offset: 0 113 | } 114 | const b = { 115 | speed: 21 116 | } 117 | expect(isScrollBarrage(a)).toBeTruthy() 118 | expect(isScrollBarrage(b)).toBeFalsy() 119 | }) 120 | 121 | test('isFixedBarrage', () => { 122 | const a = { 123 | duration: 132 124 | } 125 | const b = { 126 | speed: 12 127 | } 128 | expect(isFixedBarrage(a)).toBeTruthy() 129 | expect(isFixedBarrage(b)).toBeFalsy() 130 | }) 131 | 132 | test('requestAnimationFrame', done => { 133 | const callback = jest.fn(() => {}) 134 | const handler = requestAnimationFrame(callback) 135 | setTimeout(() => { 136 | expect(callback.mock.calls.length).toBe(1) 137 | expect(typeof handler).toBe('number') 138 | done() 139 | }, 1000) 140 | }) 141 | 142 | test('cancelAnimationFrame', done => { 143 | const callback = jest.fn(() => {}) 144 | const handler = requestAnimationFrame(callback) 145 | cancelAnimationFrame(handler) 146 | setTimeout(() => { 147 | expect(callback.mock.calls.length).toBe(0) 148 | done() 149 | }, 1000) 150 | }) 151 | }) 152 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "a-barrage", 3 | "version": "0.0.1", 4 | "description": "JavaScript Danmu(Barrage) Library", 5 | "keywords": [], 6 | "main": "dist/barrage.umd.js", 7 | "module": "dist/barrage.es5.js", 8 | "typings": "dist/types/barrage.d.ts", 9 | "files": [ 10 | "dist" 11 | ], 12 | "author": "everlastlucas ", 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/logcas/a-barrage.git" 16 | }, 17 | "license": "MIT", 18 | "engines": { 19 | "node": ">=6.0.0" 20 | }, 21 | "scripts": { 22 | "lint": "tslint --project tsconfig.json -t codeFrame 'src/**/*.ts' 'test/**/*.ts'", 23 | "prebuild": "rimraf dist", 24 | "build": "tsc --module commonjs && rollup -c rollup.config.ts && typedoc --out docs --target es6 --theme minimal --mode file src", 25 | "start": "rollup -c rollup.config.ts -w", 26 | "test": "jest --coverage", 27 | "test:watch": "jest --coverage --watch", 28 | "test:prod": "npm run lint && npm run test -- --no-cache", 29 | "deploy-docs": "ts-node tools/gh-pages-publish", 30 | "report-coverage": "cat ./coverage/lcov.info | coveralls", 31 | "commit": "git-cz", 32 | "semantic-release": "semantic-release", 33 | "semantic-release-prepare": "ts-node tools/semantic-release-prepare", 34 | "precommit": "lint-staged", 35 | "travis-deploy-once": "travis-deploy-once", 36 | "example": "webpack-dev-server --config=./example/webpack.config.js", 37 | "build:demo": "webpack --config=./example/webpack.prod.js" 38 | }, 39 | "lint-staged": { 40 | "{src,test}/**/*.ts": [ 41 | "prettier --write", 42 | "git add" 43 | ] 44 | }, 45 | "config": { 46 | "commitizen": { 47 | "path": "node_modules/cz-conventional-changelog" 48 | } 49 | }, 50 | "jest": { 51 | "transform": { 52 | ".(ts|tsx)": "ts-jest" 53 | }, 54 | "testEnvironment": "jsdom", 55 | "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", 56 | "moduleFileExtensions": [ 57 | "ts", 58 | "tsx", 59 | "js" 60 | ], 61 | "coveragePathIgnorePatterns": [ 62 | "/node_modules/", 63 | "/test/" 64 | ], 65 | "coverageThreshold": { 66 | "global": { 67 | "branches": 90, 68 | "functions": 95, 69 | "lines": 95, 70 | "statements": 95 71 | } 72 | }, 73 | "collectCoverageFrom": [ 74 | "src/**/*.{js,ts}" 75 | ] 76 | }, 77 | "prettier": { 78 | "semi": false, 79 | "singleQuote": true 80 | }, 81 | "commitlint": { 82 | "extends": [ 83 | "@commitlint/config-conventional" 84 | ] 85 | }, 86 | "devDependencies": { 87 | "@babel/core": "^7.9.6", 88 | "@babel/preset-env": "^7.9.6", 89 | "@commitlint/cli": "^7.1.2", 90 | "@commitlint/config-conventional": "^7.1.2", 91 | "@types/jest": "^23.3.14", 92 | "@types/node": "^10.11.0", 93 | "babel-loader": "^8.1.0", 94 | "colors": "^1.3.2", 95 | "commitizen": "^3.0.0", 96 | "coveralls": "^3.0.2", 97 | "cross-env": "^5.2.0", 98 | "cz-conventional-changelog": "^2.1.0", 99 | "faker": "^4.1.0", 100 | "html-webpack-plugin": "^4.3.0", 101 | "husky": "^1.0.1", 102 | "jest": "^23.6.0", 103 | "jest-config": "^23.6.0", 104 | "lint-staged": "^8.0.0", 105 | "lodash.camelcase": "^4.3.0", 106 | "prettier": "^1.14.3", 107 | "prompt": "^1.0.0", 108 | "replace-in-file": "^3.4.2", 109 | "rimraf": "^2.6.2", 110 | "rollup": "^0.67.0", 111 | "rollup-plugin-commonjs": "^9.1.8", 112 | "rollup-plugin-json": "^3.1.0", 113 | "rollup-plugin-node-resolve": "^3.4.0", 114 | "rollup-plugin-sourcemaps": "^0.4.2", 115 | "rollup-plugin-typescript2": "^0.18.0", 116 | "semantic-release": "^15.9.16", 117 | "shelljs": "^0.8.3", 118 | "travis-deploy-once": "^5.0.9", 119 | "ts-jest": "^23.10.5", 120 | "ts-node": "^7.0.1", 121 | "tslint": "^5.11.0", 122 | "tslint-config-prettier": "^1.15.0", 123 | "tslint-config-standard": "^8.0.1", 124 | "typedoc": "^0.12.0", 125 | "typescript": "^3.0.3", 126 | "webpack": "^4.43.0", 127 | "webpack-cli": "^3.3.11", 128 | "webpack-dev-server": "^3.11.0" 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/commander/css-renderer/rolling.ts: -------------------------------------------------------------------------------- 1 | import BaseCssCommander from './base-css' 2 | import { ScrollBarrageObject, CommanderConfig } from '../../types' 3 | import { isEmptyArray, getArrayRight } from '../../helper' 4 | import { TIME_PER_FRAME } from '../../constants' 5 | import Track from '../../track' 6 | import { createBarrage, appendChild } from '../../helper/css' 7 | 8 | export default class RollingCssCommander extends BaseCssCommander { 9 | constructor(el: HTMLDivElement, config: CommanderConfig) { 10 | super(el, config) 11 | } 12 | 13 | private get _defaultSpeed(): number { 14 | return (this.trackWidth / this.duration) * TIME_PER_FRAME 15 | } 16 | 17 | private get _randomSpeed(): number { 18 | return 0.8 + Math.random() * 1.3 19 | } 20 | 21 | add(barrage: ScrollBarrageObject): boolean { 22 | const trackId = this._findTrack() 23 | if (trackId === -1) { 24 | return false 25 | } 26 | // 创建弹幕DOM 27 | const { text, size, color, offset } = barrage 28 | const fontSize = size + 'px' 29 | const posLeft = offset + 'px' 30 | const danmu = createBarrage(text, color, fontSize, posLeft) 31 | appendChild(this.el, danmu) 32 | const width = danmu.offsetWidth 33 | 34 | // 计算弹幕速度 35 | const track = this.tracks[trackId] 36 | const trackOffset = track.offset 37 | const trackWidth = this.trackWidth 38 | let speed: number 39 | if (isEmptyArray(track.barrages)) { 40 | speed = this._defaultSpeed * this._randomSpeed 41 | } else { 42 | const { speed: preSpeed } = getArrayRight(track.barrages) 43 | speed = (trackWidth * preSpeed) / trackOffset 44 | } 45 | speed = Math.min(speed, this._defaultSpeed * 2) 46 | const normalizedBarrage = Object.assign({}, barrage, { 47 | offset: trackWidth, 48 | speed, 49 | width 50 | }) 51 | this.objToElm.set(normalizedBarrage, danmu) 52 | this.elmToObj.set(danmu, normalizedBarrage) 53 | track.push(normalizedBarrage) 54 | track.offset = trackWidth + normalizedBarrage.width * 1.2 55 | return true 56 | } 57 | 58 | _findTrack(): number { 59 | let idx = -1 60 | let max = -Infinity 61 | this.forEach((track, index) => { 62 | const trackOffset = track.offset 63 | if (trackOffset > this.trackWidth) { 64 | return 65 | } 66 | const t = this.trackWidth - trackOffset 67 | if (t > max) { 68 | idx = index 69 | max = t 70 | } 71 | }) 72 | return idx 73 | } 74 | 75 | _extractBarrage(): void { 76 | let isIntered: boolean 77 | for (let i = 0; i < this.waitingQueue.length; ) { 78 | isIntered = this.add(this.waitingQueue[i]) 79 | if (!isIntered) { 80 | break 81 | } 82 | this.waitingQueue.shift() 83 | } 84 | } 85 | 86 | render(): void { 87 | this._extractBarrage() 88 | const objToElm = this.objToElm 89 | const trackHeight = this.trackHeight 90 | this.forEach((track: Track, trackIndex: number) => { 91 | let shouldRemove = false 92 | let shouldRemoveIndex = -1 93 | track.forEach((barrage, barrageIndex) => { 94 | if (!objToElm.has(barrage)) { 95 | return 96 | } 97 | if (barrage.freeze) { 98 | return 99 | } 100 | const el = objToElm.get(barrage)! 101 | const offset = barrage.offset 102 | el.style.transform = `translate(${offset}px, ${trackIndex * trackHeight}px)` 103 | barrage.offset -= barrage.speed 104 | if (barrage.offset < 0 && Math.abs(barrage.offset) > barrage.width) { 105 | shouldRemove = true 106 | shouldRemoveIndex = barrageIndex 107 | } 108 | }) 109 | track.updateOffset() 110 | if (shouldRemove) { 111 | this._removeElementFromTrack(track, shouldRemoveIndex) 112 | track.remove(shouldRemoveIndex) 113 | } 114 | }) 115 | } 116 | 117 | _removeElementFromTrack(track: Track, removedIndex: number) { 118 | const barrage = track.barrages[removedIndex] 119 | if (!barrage) { 120 | return 121 | } 122 | const el = this.objToElm.get(barrage)! 123 | this.objToElm.delete(barrage) 124 | this.elmToObj.delete(el) 125 | this.removeElement(el) 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #

A-Barrage

2 |

高性能JavaScript弹幕库

3 | 4 | ## 🎦 Live Demo 5 | https://logcas.github.io/a-barrage/example/ 6 | 7 | ## 🧐 如何使用 8 | 9 | `A-Barrage`同时支持`Canvas`渲染和`HTML+CSS`的渲染模式,你可以根据实际情况采用不同的渲染引擎进行弹幕的渲染。其中,`Canvas`是非交互式渲染,也就是说,采用`Canvas`渲染的弹幕并不会有任何的交互操作,纯展示性质;`HTML+CSS`是交互式渲染,如果你的网站允许用户与弹幕之间进行一些交互(如点赞、回复等),那么可以采用`HTML+CSS`的渲染模式,它会结合浏览器的DOM事件进行响应。 10 | 11 | `A-Barrage`默认使用的是`Canvas`渲染模式。 12 | 13 | ### 🎞 使用`Canvas`进行弹幕渲染 14 | 15 | 采用`Canvas`渲染,即意味着你需要在模板中提供一个``元素: 16 | 17 | ```html 18 | 19 | ``` 20 | 21 | 然后,实例化一个`ABarrage`对象,同时传入`canvas`元素: 22 | 23 | ```js 24 | new ABarrage( 25 | '#danmu', 26 | config 27 | ) 28 | ``` 29 | 30 | 其中,`config`对象支持如下属性(全部都是可选的,如下值为默认值): 31 | 32 | ```js 33 | config = { 34 | engine: 'canvas', // 渲染引擎 canvas 或 css3 可选 35 | zoom: 1, // 文字缩放比 36 | proxyObject: null, // 事件代理触发对象 37 | usePointerEvents: true, // 屏蔽弹幕画布的点击事件 38 | maxTrack: 4, // 最大轨道数 39 | fontSize: 20, // 文字大小,单位为px 40 | fontColor: '#fff', // 文字颜色 41 | duration: 10000, // 弹幕留存时间 42 | trackHeight: 20 * 1.5 // 轨道高度,默认为默认文字的1.5倍 43 | } 44 | ``` 45 | 46 | ### ⛱ 使用`HTML+CSS`进行弹幕渲染 47 | 48 | 采用`HTML+CSS`渲染,你需要做的是准备一个`
`元素就好: 49 | 50 | ```html 51 |
52 |
53 |
55 | ``` 56 | 57 | 然后,实例化一个`ABarrage`对象,同时传入`div`元素: 58 | 59 | ```js 60 | new ABarrage( 61 | '#danmu', 62 | config 63 | ) 64 | ``` 65 | 66 | 其中,`config`对象支持如下属性(全部都是可选的,如下值为默认值): 67 | 68 | ```js 69 | config = { 70 | engine: 'css3', // 渲染引擎 canvas 或 css3 可选 71 | zoom: 1, // 文字缩放比 72 | proxyObject: null, // 事件代理触发对象 73 | usePointerEvents: true, // 屏蔽弹幕画布的点击事件 74 | maxTrack: 4, // 最大轨道数 75 | fontSize: 20, // 文字大小,单位为px 76 | fontColor: '#fff', // 文字颜色 77 | duration: 10000, // 弹幕留存时间 78 | trackHeight: 20 * 1.5, // 轨道高度,默认为默认文字的1.5倍 79 | wrapper: document.querySelector('#container') // wrapper 用于弹幕交互的事件代理,如果需要交互,则必须传入 80 | } 81 | ``` 82 | 83 | ### 通用步骤 84 | 85 | 然后,可以通过`add()`方法添加弹幕: 86 | ```js 87 | // 添加滚动弹幕 88 | instance.add(danmu, 'scroll') 89 | 90 | // 添加固定在顶部的弹幕 91 | instance.add(danmu, 'fixed-top') 92 | 93 | // 添加固定在底部的弹幕 94 | instance.add(danmu, 'fixed-bottom') 95 | ``` 96 | 97 | 其中,第一个参数是一个`RawBarrageObject`对象,它的类型是这样的: 98 | 99 | ```js 100 | RawBarrageObject { 101 | text: string // 文本 102 | color?: string // 颜色,可选 103 | size?: number // 字体大小,可选 104 | } 105 | ``` 106 | 107 | 第二个参数也是可选的,默认为`scroll`,即滚动弹幕。顶部弹幕和底部弹幕分别为:`fixed-top`、`fixed-bottom`。 108 | 109 | ## 📅 事件机制 110 | 111 | 首先,为了弹幕的正常显示,你必须拥有这样的层级: 112 | ``` 113 | ------用户视觉------- 114 | 👇 👇 👇 👇 115 | --------弹幕-------- 116 | -------播放器------- 117 | ``` 118 | 119 | 以上层级的HTML结构一般是这样的: 120 | ```html 121 |
122 |