用H5的canvas做出弹幕结果-
发布时间:08/01 来源:未知 浏览:
关键词:
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 //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); }) })();
canvas如何做出玄色配景带特效碎屑烟花
以上就是用H5的canvas做出弹幕结果的细致内容,更多请关注 百分百源码网 其它相干文章!