这次给大家带来用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> <video> <source></source> <source></source> Your browser does not support the video tag. </video> <canvas> 您的浏览器不支持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 { barrage.shoot(t); }) })();
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
以上就是用H5的canvas做出弹幕效果的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号