优化弹幕插件

This commit is contained in:
zhw2590582 committed 2019-04-27 00:09:07 +08:00
1 parent ec52781540
commit dd6a2dafda
4 files changed
+198 -122

No files matched your search

+6
View File
@@ -11,5 +11,11 @@ var art = new Artplayer({
color: '#fff', color: '#fff',
size: 14, size: 14,
maxlength: 50, maxlength: 50,
margin: [10, 20],
})], })],
});
console.info('弹幕加载中...');
art.on('artplayerPluginDanmu:loaded', () => {
console.info('弹幕准备就绪');
}); });
+105 -62
View File
@@ -168,22 +168,25 @@
this.queue = []; this.queue = [];
this.layer = null; this.layer = null;
this.isStop = false; this.isStop = false;
this.timer = null; this.animationFrameTimer = null;
this.option = Object.assign({}, Danmuku.option, option); this.option = Object.assign({}, Danmuku.option, option);
art.constructor.validator(this.option, Danmuku.scheme); art.constructor.validator(this.option, Danmuku.scheme);
art.on('video:play', this.start.bind(this)); art.on('video:play', this.start.bind(this));
art.on('video:playing', this.start.bind(this));
art.on('video:pause', this.stop.bind(this)); art.on('video:pause', this.stop.bind(this));
art.on('video:waiting', this.stop.bind(this));
art.on('destroy', this.stop.bind(this)); art.on('destroy', this.stop.bind(this));
if (typeof this.option.danmus === 'function') { if (typeof this.option.danmus === 'function') {
this.option.danmus().then(function (danmus) { this.option.danmus().then(function (danmus) {
art.emit('artplayerPluginDanmu:loaded', danmus);
danmus.forEach(_this.addToQueue.bind(_this)); danmus.forEach(_this.addToQueue.bind(_this));
_this.init(); _this.init();
art.emit('artplayerPluginDanmu:loaded', danmus);
}); });
} else { } else {
this.option.danmus.forEach(this.addToQueue); this.option.danmus.forEach(this.addToQueue.bind(this));
this.init(); this.init();
} }
} }
@@ -202,49 +205,73 @@
width: '100%', width: '100%',
height: '100%', height: '100%',
overflow: 'hidden', overflow: 'hidden',
pointerEvents: 'none' pointerEvents: 'none',
opacity: this.option.opacity
} }
}); });
} }
}, { }, {
key: "emit", key: "emit",
value: function emit(danmu) { value: function emit(danmu) {
var errorHandle = this.art.constructor.utils.errorHandle; var $player = this.art.template.$player;
errorHandle(this.layer, 'The danmuku is not ready'); danmu.$ref = this.getDanmuRef();
var _this$art$template$$p = this.art.template.$player,
playerWidth = _this$art$template$$p.clientWidth,
playerHeight = _this$art$template$$p.clientHeight;
danmu.$ref.innerText = danmu.text; danmu.$ref.innerText = danmu.text;
danmu.$ref.style.fontSize = "".concat(danmu.size || this.option.size, "px"); danmu.$ref.style.fontSize = "".concat(danmu.size || this.option.size, "px");
var _danmu$$ref = danmu.$ref, var playerWidth = Danmuku.getRect($player, 'width');
danmuWidth = _danmu$$ref.clientWidth, var danmuWidth = Danmuku.getRect(danmu.$ref, 'width');
danmuHeight = _danmu$$ref.clientHeight; danmu.$restWidth = playerWidth + danmuWidth + 5;
danmu.$ref.style.opacity = danmu.opacity || this.option.opacity; danmu.$restTime = this.option.speed;
danmu.$lastStartTime = Date.now();
danmu.$ref.style.color = danmu.color || this.option.color; danmu.$ref.style.color = danmu.color || this.option.color;
danmu.$ref.style.top = this.getDanmuTop(playerHeight, danmuHeight);
danmu.$ref.style.left = "".concat(playerWidth, "px"); danmu.$ref.style.left = "".concat(playerWidth, "px");
var translateX = -playerWidth - danmuWidth - 10; danmu.$ref.style.top = "".concat(this.getDanmuTop(), "px");
danmu.$ref.style.transform = "translateX(".concat(translateX, "px) translateY(0px) translateZ(0px)"); danmu.$ref.style.transform = "translateX(".concat(-danmu.$restWidth, "px) translateY(0px) translateZ(0px)");
danmu.$ref.style.transition = "-webkit-transform ".concat(danmu.$restTime, "s linear 0s"); danmu.$ref.style.transition = "-webkit-transform ".concat(danmu.$restTime, "s linear 0s");
danmu.$state = 'emit';
} }
}, { }, {
key: "continue", key: "suspend",
value: function _continue(danmu) { value: function suspend(danmu) {
danmu.$ref.style.transform = "translateX(".concat(translateX, "px) translateY(0px) translateZ(0px)"); var $player = this.art.template.$player;
danmu.$ref.style.transition = "-webkit-transform ".concat(danmu.$restTime, "s linear 0s");
var _Danmuku$getRect = Danmuku.getRect($player),
playerLeft = _Danmuku$getRect.left,
playerWidth = _Danmuku$getRect.width;
var _Danmuku$getRect2 = Danmuku.getRect(danmu.$ref),
danmuLeft = _Danmuku$getRect2.left;
danmu.$restTime -= (Date.now() - danmu.$lastStartTime) / 1000;
var translateX = playerWidth - (danmuLeft - playerLeft) + 5;
danmu.$ref.style.transform = "translateX(".concat(-translateX, "px) translateY(0px) translateZ(0px)");
danmu.$ref.style.transition = '-webkit-transform 0s linear 0s';
danmu.$state = 'stop';
} }
}, { }, {
key: "addToQueue", key: "addToQueue",
value: function addToQueue(danmu) { value: function addToQueue(danmu) {
var errorHandle = this.art.constructor.utils.errorHandle; var _this$art = this.art,
errorHandle(danmu.text, 'Danmu text cannot be empty'); notice = _this$art.notice,
errorHandle(typeof danmu.time === 'number', 'Danmu time cannot be empty'); player = _this$art.player;
errorHandle(danmu.text.length <= this.option.maxlength, "The length of the danmu does not exceed ".concat(this.option.maxlength));
if (!danmu.text.trim()) {
notice('Danmu text cannot be empty');
return;
}
if (danmu.text.length > this.option.maxlength) {
notice("The length of the danmu does not exceed ".concat(this.option.maxlength));
return;
}
if (typeof danmu.time !== 'number') {
danmu.time = player.currentTime;
}
this.queue.push(objectSpread({}, danmu, { this.queue.push(objectSpread({}, danmu, {
$state: 'wait', $state: 'wait',
$ref: null, $ref: null,
$restTime: 0, $restTime: 0
$lastPlayTime: 0
})); }));
} }
}, { }, {
@@ -254,14 +281,14 @@
var _this$art$constructor = this.art.constructor.utils, var _this$art$constructor = this.art.constructor.utils,
setStyles = _this$art$constructor.setStyles, setStyles = _this$art$constructor.setStyles,
append = _this$art$constructor.append; append = _this$art$constructor.append;
var playerLeft = $player.getBoundingClientRect().left; var playerLeft = Danmuku.getRect($player, 'left');
var waitDanmu = this.queue.find(function (danmu) { var waitDanmu = this.queue.find(function (danmu) {
if (danmu.$ref) { if (danmu.$ref) {
var _danmu$$ref$getBoundi = danmu.$ref.getBoundingClientRect(), var _Danmuku$getRect3 = Danmuku.getRect(danmu.$ref),
left = _danmu$$ref$getBoundi.left, danmuLeft = _Danmuku$getRect3.left,
width = _danmu$$ref$getBoundi.width; danmuWidth = _Danmuku$getRect3.width;
return playerLeft >= left + width; return danmu.$state === 'emit' && playerLeft > danmuLeft + danmuWidth;
} }
return false; return false;
@@ -293,18 +320,22 @@
} }
}, { }, {
key: "getDanmuTop", key: "getDanmuTop",
value: function getDanmuTop(playerHeight, danmuHeight) { value: function getDanmuTop() {
return 0; var $player = this.art.template.$player;
} var playerHeight = Danmuku.getRect($player, 'height');
}, { var danmus = this.queue.filter(function (danmu) {
key: "changeState", return danmu.$state === 'emit';
value: function changeState(before, after) {
return this.queue.filter(function (danmu) {
return danmu.$state === before;
}).map(function (danmu) {
danmu.$state = after;
return danmu;
}); });
if (danmus.length === 0) {
return this.option.margin[0];
}
if (danmus.length === 1) {
return this.option.margin[0] + Danmuku.getRect(danmus[0].$ref, 'height');
}
return 0;
} }
}, { }, {
key: "update", key: "update",
@@ -312,18 +343,14 @@
var _this2 = this; var _this2 = this;
var player = this.art.player; var player = this.art.player;
this.timer = window.requestAnimationFrame(function () { this.animationFrameTimer = window.requestAnimationFrame(function () {
_this2.queue.filter(function (danmu) { if (_this2.layer && player.playing) {
return player.currentTime + 0.25 >= danmu.time && danmu.time >= player.currentTime - 0.25 && danmu.$state === 'wait'; _this2.queue.filter(function (danmu) {
}).map(function (danmu) { return player.currentTime + 0.25 >= danmu.time && danmu.time >= player.currentTime - 0.25 && danmu.$state === 'wait';
danmu.$lastPlayTime = Date.now(); }).forEach(function (danmu) {
danmu.$restTime = _this2.option.speed; _this2.emit(danmu);
danmu.$ref = _this2.getDanmuRef(); });
danmu.$state = 'emit'; }
return danmu;
}).forEach(function (danmu) {
_this2.emit(danmu);
});
if (!_this2.isStop) { if (!_this2.isStop) {
_this2.update(); _this2.update();
@@ -333,14 +360,15 @@
}, { }, {
key: "stop", key: "stop",
value: function stop() { value: function stop() {
var _this3 = this;
this.isStop = true; this.isStop = true;
this.queue.filter(function (danmu) { this.queue.filter(function (danmu) {
return danmu.$state === 'emit'; return danmu.$state === 'emit';
}).forEach(function (danmu) { }).forEach(function (danmu) {
danmu.$state = 'stop'; _this3.suspend(danmu);
danmu.$restTime -= Date.now() - danmu.$lastPlayTime;
}); });
window.cancelAnimationFrame(this.timer); window.cancelAnimationFrame(this.animationFrameTimer);
this.art.emit('artplayerPluginDanmu:stop'); this.art.emit('artplayerPluginDanmu:stop');
} }
}, { }, {
@@ -350,8 +378,7 @@
this.queue.filter(function (danmu) { this.queue.filter(function (danmu) {
return danmu.$state === 'stop'; return danmu.$state === 'stop';
}).forEach(function (danmu) { }).forEach(function (danmu) {
danmu.$state = 'emit'; Danmuku["continue"](danmu);
danmu.$lastPlayTime = Date.now();
}); });
this.update(); this.update();
this.art.emit('artplayerPluginDanmu:start'); this.art.emit('artplayerPluginDanmu:start');
@@ -369,6 +396,20 @@
this.art.emit('artplayerPluginDanmu:hide'); this.art.emit('artplayerPluginDanmu:hide');
} }
}], [{ }], [{
key: "getRect",
value: function getRect(ref, key) {
var result = ref.getBoundingClientRect();
return key ? result[key] : result;
}
}, {
key: "continue",
value: function _continue(danmu) {
danmu.$lastStartTime = Date.now();
danmu.$ref.style.transform = "translateX(".concat(-danmu.$restWidth, "px) translateY(0px) translateZ(0px)");
danmu.$ref.style.transition = "-webkit-transform ".concat(danmu.$restTime, "s linear 0s");
danmu.$state = 'emit';
}
}, {
key: "option", key: "option",
get: function get() { get: function get() {
return { return {
@@ -376,8 +417,9 @@
speed: 5, speed: 5,
opacity: 1, opacity: 1,
color: '#fff', color: '#fff',
size: 14, size: 25,
maxlength: 50 maxlength: 50,
margin: [10, 20]
}; };
} }
}, { }, {
@@ -389,7 +431,8 @@
opacity: 'number', opacity: 'number',
color: 'string', color: 'string',
size: 'number', size: 'number',
maxlength: 'number' maxlength: 'number',
margin: 'array'
}; };
} }
}]); }]);
@@ -1 +1 @@
{"version":3,"file":"artplayer-plugin-danmu.js","sources":["../../node_modules/@babel/runtime/helpers/arrayWithHoles.js","../../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js","../../node_modules/@babel/runtime/helpers/nonIterableRest.js","../../node_modules/@babel/runtime/helpers/slicedToArray.js","../../packages/artplayer-plugin-danmu/src/bilibiliDanmuParse.js","../../node_modules/@babel/runtime/helpers/defineProperty.js","../../node_modules/@babel/runtime/helpers/objectSpread.js","../../node_modules/@babel/runtime/helpers/classCallCheck.js","../../node_modules/@babel/runtime/helpers/createClass.js","../../packages/artplayer-plugin-danmu/src/danmuku.js","../../packages/artplayer-plugin-danmu/src/index.js"],"sourcesContent":["function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nmodule.exports = _arrayWithHoles;","function _iterableToArrayLimit(arr, i) {\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nmodule.exports = _iterableToArrayLimit;","function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n}\n\nmodule.exports = _nonIterableRest;","var arrayWithHoles = require(\"./arrayWithHoles\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit\");\n\nvar nonIterableRest = require(\"./nonIterableRest\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray;","export function bilibiliDanmuParseFromXml(xmlString) {\n if (typeof xmlString !== 'string') return [];\n const srtList = xmlString.match(/<d([\\S ]*?>[\\S ]*?)<\\/d>/gi);\n return srtList.length\n ? srtList.map(item => {\n const [, attrStr, text] = item.match(/<d p=\"(.+)\">(.+)<\\/d>/);\n const attr = attrStr.split(',');\n return attr.length === 8 && text.trim()\n ? {\n text,\n time: Number(attr[0]),\n mode: Number(attr[1]),\n size: Number(attr[2]),\n color: `#${Number(attr[3]).toString(16)}`,\n timestamp: Number(attr[4]),\n pool: Number(attr[5]),\n userID: attr[6],\n rowID: Number(attr[7]),\n }\n : null;\n })\n : [];\n}\n\nexport function bilibiliDanmuParseFromAv(av) {\n const corsUrl = 'https://cors-anywhere.herokuapp.com/';\n return fetch(`${corsUrl}https://api.bilibili.com/x/web-interface/view?aid=${av}`)\n .then(res => res.json())\n .then(res => {\n if (res.code === 0 && res.data && res.data.cid) {\n return fetch(`${corsUrl}https://api.bilibili.com/x/v1/dm/list.so?oid=${res.data.cid}`)\n .then(res => res.text())\n .then(xmlString => {\n return bilibiliDanmuParseFromXml(xmlString);\n });\n }\n throw new Error(`Unable to get data: ${JSON.stringify(res)}`);\n });\n}","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;","var defineProperty = require(\"./defineProperty\");\n\nfunction _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nmodule.exports = _objectSpread;","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck;","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.definePrLine truncated {"version":3,"file":"artplayer-plugin-danmu.js","sources":["../../node_modules/@babel/runtime/helpers/arrayWithHoles.js","../../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js","../../node_modules/@babel/runtime/helpers/nonIterableRest.js","../../node_modules/@babel/runtime/helpers/slicedToArray.js","../../packages/artplayer-plugin-danmu/src/bilibiliDanmuParse.js","../../node_modules/@babel/runtime/helpers/defineProperty.js","../../node_modules/@babel/runtime/helpers/objectSpread.js","../../node_modules/@babel/runtime/helpers/classCallCheck.js","../../node_modules/@babel/runtime/helpers/createClass.js","../../packages/artplayer-plugin-danmu/src/danmuku.js","../../packages/artplayer-plugin-danmu/src/index.js"],"sourcesContent":["function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\n\nmodule.exports = _arrayWithHoles;","function _iterableToArrayLimit(arr, i) {\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"] != null) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n\n return _arr;\n}\n\nmodule.exports = _iterableToArrayLimit;","function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n}\n\nmodule.exports = _nonIterableRest;","var arrayWithHoles = require(\"./arrayWithHoles\");\n\nvar iterableToArrayLimit = require(\"./iterableToArrayLimit\");\n\nvar nonIterableRest = require(\"./nonIterableRest\");\n\nfunction _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();\n}\n\nmodule.exports = _slicedToArray;","export function bilibiliDanmuParseFromXml(xmlString) {\n if (typeof xmlString !== 'string') return [];\n const srtList = xmlString.match(/<d([\\S ]*?>[\\S ]*?)<\\/d>/gi);\n return srtList.length\n ? srtList.map(item => {\n const [, attrStr, text] = item.match(/<d p=\"(.+)\">(.+)<\\/d>/);\n const attr = attrStr.split(',');\n return attr.length === 8 && text.trim()\n ? {\n text,\n time: Number(attr[0]),\n mode: Number(attr[1]),\n size: Number(attr[2]),\n color: `#${Number(attr[3]).toString(16)}`,\n timestamp: Number(attr[4]),\n pool: Number(attr[5]),\n userID: attr[6],\n rowID: Number(attr[7]),\n }\n : null;\n })\n : [];\n}\n\nexport function bilibiliDanmuParseFromAv(av) {\n const corsUrl = 'https://cors-anywhere.herokuapp.com/';\n return fetch(`${corsUrl}https://api.bilibili.com/x/web-interface/view?aid=${av}`)\n .then(res => res.json())\n .then(res => {\n if (res.code === 0 && res.data && res.data.cid) {\n return fetch(`${corsUrl}https://api.bilibili.com/x/v1/dm/list.so?oid=${res.data.cid}`)\n .then(res => res.text())\n .then(xmlString => {\n return bilibiliDanmuParseFromXml(xmlString);\n });\n }\n throw new Error(`Unable to get data: ${JSON.stringify(res)}`);\n });\n}","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;","var defineProperty = require(\"./defineProperty\");\n\nfunction _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n\n if (typeof Object.getOwnPropertySymbols === 'function') {\n ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n }));\n }\n\n ownKeys.forEach(function (key) {\n defineProperty(target, key, source[key]);\n });\n }\n\n return target;\n}\n\nmodule.exports = _objectSpread;","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck;","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.definePrLine truncated
+86 -59
View File
@@ -4,20 +4,22 @@ export default class Danmuku {
this.queue = []; this.queue = [];
this.layer = null; this.layer = null;
this.isStop = false; this.isStop = false;
this.timer = null; this.animationFrameTimer = null;
this.option = Object.assign({}, Danmuku.option, option); this.option = Object.assign({}, Danmuku.option, option);
art.constructor.validator(this.option, Danmuku.scheme); art.constructor.validator(this.option, Danmuku.scheme);
art.on('video:play', this.start.bind(this)); art.on('video:play', this.start.bind(this));
art.on('video:playing', this.start.bind(this));
art.on('video:pause', this.stop.bind(this)); art.on('video:pause', this.stop.bind(this));
art.on('video:waiting', this.stop.bind(this));
art.on('destroy', this.stop.bind(this)); art.on('destroy', this.stop.bind(this));
if (typeof this.option.danmus === 'function') { if (typeof this.option.danmus === 'function') {
this.option.danmus().then(danmus => { this.option.danmus().then(danmus => {
art.emit('artplayerPluginDanmu:loaded', danmus);
danmus.forEach(this.addToQueue.bind(this)); danmus.forEach(this.addToQueue.bind(this));
this.init(); this.init();
art.emit('artplayerPluginDanmu:loaded', danmus);
}); });
} else { } else {
this.option.danmus.forEach(this.addToQueue); this.option.danmus.forEach(this.addToQueue.bind(this));
this.init(); this.init();
} }
} }
@@ -28,8 +30,9 @@ export default class Danmuku {
speed: 5, speed: 5,
opacity: 1, opacity: 1,
color: '#fff', color: '#fff',
size: 14, size: 25,
maxlength: 50, maxlength: 50,
margin: [10, 20],
}; };
} }
@@ -41,9 +44,15 @@ export default class Danmuku {
color: 'string', color: 'string',
size: 'number', size: 'number',
maxlength: 'number', maxlength: 'number',
margin: 'array',
}; };
} }
static getRect(ref, key) {
const result = ref.getBoundingClientRect();
return key ? result[key] : result;
}
init() { init() {
this.layer = this.art.layers.add({ this.layer = this.art.layers.add({
name: 'danmu', name: 'danmu',
@@ -57,57 +66,80 @@ export default class Danmuku {
height: '100%', height: '100%',
overflow: 'hidden', overflow: 'hidden',
pointerEvents: 'none', pointerEvents: 'none',
opacity: this.option.opacity,
}, },
}); });
} }
emit(danmu) { emit(danmu) {
const { errorHandle } = this.art.constructor.utils; const { $player } = this.art.template;
errorHandle(this.layer, 'The danmuku is not ready'); danmu.$ref = this.getDanmuRef();
const { clientWidth: playerWidth, clientHeight: playerHeight } = this.art.template.$player;
danmu.$ref.innerText = danmu.text; danmu.$ref.innerText = danmu.text;
danmu.$ref.style.fontSize = `${danmu.size || this.option.size}px`; danmu.$ref.style.fontSize = `${danmu.size || this.option.size}px`;
const { clientWidth: danmuWidth, clientHeight: danmuHeight } = danmu.$ref; const playerWidth = Danmuku.getRect($player, 'width');
danmu.$ref.style.opacity = danmu.opacity || this.option.opacity; const danmuWidth = Danmuku.getRect(danmu.$ref, 'width');
danmu.$restWidth = playerWidth + danmuWidth + 5;
danmu.$restTime = this.option.speed;
danmu.$lastStartTime = Date.now();
danmu.$ref.style.color = danmu.color || this.option.color; danmu.$ref.style.color = danmu.color || this.option.color;
danmu.$ref.style.top = this.getDanmuTop(playerHeight, danmuHeight);
danmu.$ref.style.left = `${playerWidth}px`; danmu.$ref.style.left = `${playerWidth}px`;
const translateX = -playerWidth - danmuWidth - 10; danmu.$ref.style.top = `${this.getDanmuTop()}px`;
danmu.$ref.style.transform = `translateX(${translateX}px) translateY(0px) translateZ(0px)`; danmu.$ref.style.transform = `translateX(${-danmu.$restWidth}px) translateY(0px) translateZ(0px)`;
danmu.$ref.style.transition = `-webkit-transform ${danmu.$restTime}s linear 0s`; danmu.$ref.style.transition = `-webkit-transform ${danmu.$restTime}s linear 0s`;
danmu.$state = 'emit';
} }
continue(danmu) { static continue(danmu) {
danmu.$ref.style.transform = `translateX(${translateX}px) translateY(0px) translateZ(0px)`; danmu.$lastStartTime = Date.now();
danmu.$ref.style.transform = `translateX(${-danmu.$restWidth}px) translateY(0px) translateZ(0px)`;
danmu.$ref.style.transition = `-webkit-transform ${danmu.$restTime}s linear 0s`; danmu.$ref.style.transition = `-webkit-transform ${danmu.$restTime}s linear 0s`;
danmu.$state = 'emit';
}
suspend(danmu) {
const { $player } = this.art.template;
const { left: playerLeft, width: playerWidth } = Danmuku.getRect($player);
const { left: danmuLeft } = Danmuku.getRect(danmu.$ref);
danmu.$restTime -= (Date.now() - danmu.$lastStartTime) / 1000;
const translateX = playerWidth - (danmuLeft - playerLeft) + 5;
danmu.$ref.style.transform = `translateX(${-translateX}px) translateY(0px) translateZ(0px)`;
danmu.$ref.style.transition = '-webkit-transform 0s linear 0s';
danmu.$state = 'stop';
} }
addToQueue(danmu) { addToQueue(danmu) {
const { errorHandle } = this.art.constructor.utils; const { notice, player } = this.art;
errorHandle(danmu.text, 'Danmu text cannot be empty'); if (!danmu.text.trim()) {
errorHandle(typeof danmu.time === 'number', 'Danmu time cannot be empty'); notice('Danmu text cannot be empty');
errorHandle( return;
danmu.text.length <= this.option.maxlength, }
`The length of the danmu does not exceed ${this.option.maxlength}`,
); if (danmu.text.length > this.option.maxlength) {
notice(`The length of the danmu does not exceed ${this.option.maxlength}`);
return;
}
if (typeof danmu.time !== 'number') {
danmu.time = player.currentTime;
}
this.queue.push({ this.queue.push({
...danmu, ...danmu,
$state: 'wait', $state: 'wait',
$ref: null, $ref: null,
$restTime: 0, $restTime: 0,
$lastPlayTime: 0,
}); });
} }
getDanmuRef() { getDanmuRef() {
const { $player } = this.art.template; const { $player } = this.art.template;
const { setStyles, append } = this.art.constructor.utils; const { setStyles, append } = this.art.constructor.utils;
const playerLeft = $player.getBoundingClientRect().left; const playerLeft = Danmuku.getRect($player, 'left');
const waitDanmu = this.queue.find(danmu => { const waitDanmu = this.queue.find(danmu => {
if (danmu.$ref) { if (danmu.$ref) {
const { left, width } = danmu.$ref.getBoundingClientRect(); const { left: danmuLeft, width: danmuWidth } = Danmuku.getRect(danmu.$ref);
return playerLeft >= left + width; return danmu.$state === 'emit' && playerLeft > danmuLeft + danmuWidth;
} }
return false; return false;
}); });
@@ -140,40 +172,37 @@ export default class Danmuku {
return $ref; return $ref;
} }
getDanmuTop(playerHeight, danmuHeight) { getDanmuTop() {
return 0; const { $player } = this.art.template;
} const playerHeight = Danmuku.getRect($player, 'height');
const danmus = this.queue.filter(danmu => danmu.$state === 'emit');
if (danmus.length === 0) {
return this.option.margin[0];
}
changeState(before, after) { if (danmus.length === 1) {
return this.queue return this.option.margin[0] + Danmuku.getRect(danmus[0].$ref, 'height');
.filter(danmu => danmu.$state === before) }
.map(danmu => {
danmu.$state = after; return 0;
return danmu;
});
} }
update() { update() {
const { player } = this.art; const { player } = this.art;
this.timer = window.requestAnimationFrame(() => { this.animationFrameTimer = window.requestAnimationFrame(() => {
this.queue if (this.layer && player.playing) {
.filter(danmu => { this.queue
return ( .filter(danmu => {
player.currentTime + 0.25 >= danmu.time && return (
danmu.time >= player.currentTime - 0.25 && player.currentTime + 0.25 >= danmu.time &&
danmu.$state === 'wait' danmu.time >= player.currentTime - 0.25 &&
); danmu.$state === 'wait'
}) );
.map(danmu => { })
danmu.$lastPlayTime = Date.now(); .forEach(danmu => {
danmu.$restTime = this.option.speed; this.emit(danmu);
danmu.$ref = this.getDanmuRef(); });
danmu.$state = 'emit'; }
return danmu;
})
.forEach(danmu => {
this.emit(danmu);
});
if (!this.isStop) { if (!this.isStop) {
this.update(); this.update();
@@ -186,10 +215,9 @@ export default class Danmuku {
this.queue this.queue
.filter(danmu => danmu.$state === 'emit') .filter(danmu => danmu.$state === 'emit')
.forEach(danmu => { .forEach(danmu => {
danmu.$state = 'stop'; this.suspend(danmu);
danmu.$restTime -= Date.now() - danmu.$lastPlayTime;
}); });
window.cancelAnimationFrame(this.timer); window.cancelAnimationFrame(this.animationFrameTimer);
this.art.emit('artplayerPluginDanmu:stop'); this.art.emit('artplayerPluginDanmu:stop');
} }
@@ -198,8 +226,7 @@ export default class Danmuku {
this.queue this.queue
.filter(danmu => danmu.$state === 'stop') .filter(danmu => danmu.$state === 'stop')
.forEach(danmu => { .forEach(danmu => {
danmu.$state = 'emit'; Danmuku.continue(danmu);
danmu.$lastPlayTime = Date.now();
}); });
this.update(); this.update();
this.art.emit('artplayerPluginDanmu:start'); this.art.emit('artplayerPluginDanmu:start');