这次给大家带来用h5的canvas做出弹幕效果,用h5的canvas做出弹幕效果的注意事项有哪些,下面就是实战案例,一起来看一下。
canvas知识
绘制文字
let canvas = document.getelementbyid('canvas');let ctx = canvas.getcontext('2d');ctx.font = '20px microsoft yahei'; //字体、大小ctx.fillstyle = '#000000'; //字体颜色ctx.filltext('canvas 绘制文字', 100, 100); //文本,字体x,y坐标
文本宽度
ctx.measuretext('文本宽度').width
清除绘制内容
ctx.clearrect(0, 0, width, height);
实现步骤
1、创建canvas元素利用绝对定位覆盖在视频上
2、创建barrage类,添加的弹幕缓存到弹幕列表中,并记录相应弹幕信息
3、绘制弹幕文本,用文本偏移量控制移动速度
4、计算当文本超出画布时移出弹幕列表
代码
//html<div style="position:relative;width:500px;height:400px;text-align:center;">
<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>//js(function () { class barrage {
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);
} //获取随机top
gettop() { //canvas绘制文字x,y坐标是按文字左下角计算,预留30px
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);
})
})();
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
前端开发中的svg动画
canvas怎样做出黑色背景带特效碎屑烟花
以上就是用h5的canvas做出弹幕效果的详细内容。