// 弹幕方法
import icon3 from "../../img/barrage/3@2x.png";
let barrageArr = [icon3, icon4, icon5, icon6, icon7, icon8, icon9, icon10, icon11, icon12, icon13, icon14, icon15, icon16, icon17];
let isStop = false;
var subIndex = 0,
xIndex = 0,
trackArr = [0, 60, 120, 180, 240, 300, 0, 60, 120, 180, 240, 300, 0, 60, 120];
isStop = false;
var canvasBarrage = function (canvas, data) {
if (!canvas || !data || !data.length) {
return;
}
if (typeof canvas == 'string') {
canvas = document.querySelector(canvas);
canvasBarrage(canvas, data);
return;
}
var context = canvas.getContext('2d');
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
// 内存中先加载,然后当内存加载完毕时,再把内存中的数据填充到我们的 dom元素中,这样能够快速的去
// 反应,比如网易的图片
// 存储实例
var store = {};
// 字号大小
// 实例方法
var Barrage = function (obj, index) {
// 随机x坐标也就是横坐标,对于y纵坐标,以及变化量moveX
// this.x = (1 + index * 0.1 / Math.random()) * canvas.width;
this.x = (1 + xIndex * RATE_POINT_8) * canvas.width;
// this.y = obj.range[0] * canvas.height + (obj.range[1] - obj.range[0]) * canvas.height * Math.random() + 42;
this.y = trackArr[subIndex];
subIndex++;
xIndex++;
if (subIndex >= 15) {
subIndex = 0;
}
this.moveX = 3;
this.params = obj;
this.drawCommon = function () {
var img = new Image();
img.onload = () => {
// 将图片画到canvas上面上去!
context.drawImage(img, this.x, this.y);
};
img.src = barrageArr[index];
context.drawImage(img, this.x, this.y);
};
};
data.forEach(function (obj, index) {
store[index] = new Barrage(obj, index);
});
// 绘制弹幕文本
var draw = function () {
for (var index in store) {
var barrage = store[index];
// 位置变化
barrage.x -= barrage.moveX;
if (barrage.x < -1 * canvas.width * 1.5) {
// barrage.x = (1 + index * 0.1 / Math.random()) * canvas.width;
// 移动到画布外部时候从左侧开始继续位移
barrage.x = (1 + xIndex * RATE_POINT_8) * canvas.width;
// barrage.y = (barrage.params.range[0] + (barrage.params.range[1] - barrage.params.range[0]) * Math.random()) * canvas.height;
// if (barrage.y < fontSize) {
// barrage.y = fontSize;
// } else if (barrage.y > canvas.height - fontSize) {
// barrage.y = canvas.height - fontSize;
// }
barrage.y = trackArr[subIndex];
subIndex++;
xIndex++;
if (subIndex >= 15) {
subIndex = 0;
}
// barrage.moveX = 1 + Math.random() * 3;
barrage.moveX = 3;
}
// 根据新位置绘制圆圈圈
store[index].drawCommon();
}
};
// 画布渲染
var render = function () {
if (isStop) {
return
}
// 清除画布
context.clearRect(0, 0, canvas.width, canvas.height);
// 绘制画布上所有的圆圈圈
draw();
// 继续渲染
requestAnimationFrame(render);
};
render();
};
canvasBarrage('#canvasBarrage', barrageArr);