<video controls=
"controls"
autoplay=
"autoplay"
style=
"width:100%;height:100%;"
>
<source src=
"http://www.w3school.com.cn/i/movie.ogg"
type=
"video/ogg"
/>
<source src=
"http://www.w3school.com.cn/i/movie.mp4"
type=
"video/mp4"
/>
Your browser does not support the video tag.
</video>
<canvas id=
"canvas"
width=
"500"
height=
"400"
style=
"position:absolute;top:0;left:0;"
>
您的浏览器不支持canvas标签。
</canvas>
</div>
constructor(canvas) {
this.canvas = document.getElementById(canvas);
let rect = this.canvas.getBoundingClientRect();
this.w = rect.right - rect.left;
this.h = rect.bottom - rect.top;
this.ctx = this.canvas.getContext(
'2d'
);
this.ctx.font =
'20px Microsoft YaHei'
;
this.barrageList = [];
}
shoot(value) {
let top = this.getTop();
let color = this.getColor();
let offset = this.getOffset();
let width = Math.
ceil
(this.ctx.measureText(value).width);
let barrage = {
value: value,
top: top,
left: this.w,
color: color,
offset: offset,
width: width
}
this.barrageList.push(barrage);
}
draw() {
if
(this.barrageList.length) {
this.ctx.clearRect(0, 0, this.w, this.h);
for
(let i = 0; i < this.barrageList.length; i++) {
let b = this.barrageList[i];
if
(b.left + b.width <= 0) {
this.barrageList.splice(i, 1);
i--;
continue
;
}
b.left -= b.offset;
this.drawText(b);
}
}
requestAnimationFrame(this.draw.bind(this));
}
drawText(barrage) {
this.ctx.fillStyle = barrage.color;
this.ctx.fillText(barrage.value, barrage.left, barrage.top);
}
getColor() {
return
'#'
+ Math.
floor
(Math.random() * 0xffffff).toString(16);
}
getTop() {
return
Math.
floor
(Math.random() * (this.h - 30)) + 30;
}
getOffset() {
return
+(Math.random() * 4).toFixed(1) + 1;
}
}
let barrage =
new
Barrage(
'canvas'
);
barrage.draw();
const
textList = [
'弹幕'
,
'666'
,
'233333333'
,
'javascript'
,
'html'
,
'css'
,
'前端框架'
,
'Vue'
,
'React'
,
'Angular'
,
'测试弹幕效果'
];
textList.forEach((t) => {
barrage.shoot(t);
})
})();