javascript实现视频弹幕效果(两个版本)

yizhihongxing

Javascript实现视频弹幕效果攻略

1. 引言

弹幕是指用户在观看视频时,能够发送一些评论消息,这些评论消息会以滚动、飘动、静态等形式浮现在视频画面上方。在现在各大视频平台上,弹幕已成为视频观看的一种重要要素。

本篇攻略将从两个版本的弹幕效果的具体实现入手,来详细讲解JavaScript实现弹幕效果的过程。

2. 版本一

2.1 函数封装

本案例中主要使用了JavaScript来实现弹幕的效果。首先我们可以通过定义一个弹幕函数来实现弹幕的滚动效果。

/**
 * [danmu 动态弹幕]
 * @param  {[string]} text  [文字]
 * @param  {[number]} size  [文字大小]
 * @param  {[string]} color [文字颜色]
 * @return {[object]}       [返回弹幕节点]
 */
function danmu(text, size, color) {
  // 创建一个div标签,用于存放弹幕
  const div = document.createElement('div');
  div.style.position = 'fixed';
  div.style.whiteSpace = 'nowrap';
  div.innerText = text;
  div.style.fontSize = size + 'px';
  div.style.color = color;
  // 将弹幕div节点放入DOM中
  document.body.appendChild(div);
  // 返回该弹幕节点对象
  return div;
}

该函数中传入三个参数,分别为文字、文字大小和文字颜色,并返回一个弹幕节点。

2.2 发送弹幕

我们可以通过JS实现一个弹幕发送器,可以在键盘事件中监听输入的内容,用户输入文字后可以通过该函数向弹幕画面添加弹幕。

/**
 * [sendDanmu 发送弹幕]
 * @return {[type]} [description]
 */
function sendDanmu() {
  // 获取input框
  const input = document.querySelector('input');
  // 获取input框中的value值
  const text = input.value;
  // 清空input框中的value值
  input.value = '';
  // 随机设置文字大小和颜色
  const size = Math.floor(Math.random() * 40 + 20);
  const color = `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`;
  // 调用danmu函数创建弹幕节点
  const node = danmu(text, size, color);
  // 设置初始位置
  node.style.top = Math.floor(Math.random() * (window.innerHeight - node.offsetHeight)) + 'px';
  // 设置弹幕移动速度,移动速度越快表示飞的越快
  const speed = Math.floor(Math.random() * 10 + 5);
  // 设置弹幕的动画
  const animate = node.animate([
    { 
      transform: `translateX(${window.innerWidth}px)` 
    },
    { 
      transform: `translateX(-${node.offsetWidth}px)` 
    }
  ], speed * 1000);
  // 监听动画结束事件,在动画结束后从DOM节点中删除
  animate.addEventListener('finish', () => {
    node.parentNode.removeChild(node);
  });
}

2.3 示例

在上述弹幕发送器的基础上,我们可以实现一个简单的弹幕示例。用户在输入框中输入文字后,点击发送,所输入的文字会出现在屏幕上方,以滚动的方式从右往左飘出。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Danmu Demo1</title>
  </head>
  <body>
    <input type="text" onkeydown="if(event.keyCode===13) sendDanmu()">
    <button onclick="sendDanmu()">发送</button>
    <script>
      /**
       * [danmu 动态弹幕]
       * @param  {[string]} text  [文字]
       * @param  {[number]} size  [文字大小]
       * @param  {[string]} color [文字颜色]
       * @return {[object]}       [返回弹幕节点]
       */
      function danmu(text, size, color) {
        // 创建一个div标签,用于存放弹幕
        const div = document.createElement('div');
        div.style.position = 'fixed';
        div.style.whiteSpace = 'nowrap';
        div.innerText = text;
        div.style.fontSize = size + 'px';
        div.style.color = color;
        // 将弹幕div节点放入DOM中
        document.body.appendChild(div);
        // 返回该弹幕节点对象
        return div;
      }

      /**
       * [sendDanmu 发送弹幕]
       * @return {[type]} [description]
       */
      function sendDanmu() {
        // 获取input框
        const input = document.querySelector('input');
        // 获取input框中的value值
        const text = input.value;
        // 清空input框中的value值
        input.value = '';
        // 随机设置文字大小和颜色
        const size = Math.floor(Math.random() * 40 + 20);
        const color = `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`;
        // 调用danmu函数创建弹幕节点
        const node = danmu(text, size, color);
        // 设置初始位置
        node.style.top = Math.floor(Math.random() * (window.innerHeight - node.offsetHeight)) + 'px';
        // 设置弹幕移动速度,移动速度越快表示飞的越快
        const speed = Math.floor(Math.random() * 10 + 5);
        // 设置弹幕的动画
        const animate = node.animate([
          { 
            transform: `translateX(${window.innerWidth}px)` 
          },
          { 
            transform: `translateX(-${node.offsetWidth}px)` 
          }
        ], speed * 1000);
        // 监听动画结束事件,在动画结束后从DOM节点中删除
        animate.addEventListener('finish', () => {
          node.parentNode.removeChild(node);
        });
      }
    </script>
  </body>
</html>

3. 版本二

3.1 函数封装

除了可以实现上述弹幕的简单示例外,我们还可以使用Canvas来实现更复杂的弹幕效果。在这种情况下,我们需要使用JavaScript的canvas绘图技术来绘制弹幕,可以将以下函数用于创建画布和绘制弹幕。

/**
 * [createCanvas 创建画布]
 * @return {[object]} [canvas对象]
 */
function createCanvas() {
  // 创建canvas节点
  const canvas = document.createElement('canvas');
  // 设置canvas宽高和样式
  canvas.setAttribute('width', window.innerWidth);
  canvas.setAttribute('height', window.innerHeight);
  canvas.style.position = 'fixed';
  canvas.style.top = '0';
  canvas.style.left = '0';
  canvas.style.zIndex = '100';
  // 将canvas节点插入到DOM中
  document.body.appendChild(canvas);
  // 返回canvas对象
  return canvas;
}

/**
 * [danmuCanvas 动态弹幕画布]
 * @param  {[string]} text  [文字]
 * @param  {[number]} size  [文字大小]
 * @param  {[string]} color [文字颜色]
 */
function danmuCanvas(text, size, color) {
  this.text = text;
  this.size = size;
  this.color = color;
  // 获取canvas窗口宽度和高度
  const canvasWidth = canvas.width;
  const canvasHeight = canvas.height;
  // 设置初始位置
  this.x = canvasWidth;
  this.y = Math.floor(Math.random() * (canvasHeight - size));
  // 设置弹幕移动速度,移动速度越快表示飞的越快
  const speed = Math.floor(Math.random() * 10 + 5);
  // 绘制弹幕
  this.draw = function() {
    // 获取canvas上下文
    const context = canvas.getContext('2d');
    // 设置字体大小和颜色
    context.font = size + 'px sans-serif';
    context.fillStyle = color;
    // 绘制弹幕文字
    context.fillText(text, this.x, this.y);
  };
  // 更新弹幕位置
  this.update = function() {
    this.x -= speed;
    // 判断弹幕是否超出屏幕
    if (this.x < -canvasWidth) {
      removeDanmu(this);
    }
  };
}

3.2 发送弹幕

我们可以通过点击事件调用该函数,来向画布中添加弹幕。

/**
 * [sendDanmuCanvas 发送弹幕画布]
 * @return {[type]} [description]
 */
function sendDanmuCanvas() {
  // 获取input框
  const input = document.querySelector('input');
  // 获取input框中的value值
  const text = input.value;
  // 清空input框中的value值
  input.value = '';
  // 随机设置文字大小和颜色
  const size = Math.floor(Math.random() * 40 + 20);
  const color = `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`;
  // 创建一条弹幕
  const danmu = new danmuCanvas(text, size, color);
  // 将弹幕放入弹幕数组中
  danmus.push(danmu);
}

3.3 示例

在该版本中,我们需要一个canvas标签来作为弹幕画布,可以通过以下代码实现。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Danmu Demo2</title>
  </head>
  <body>
    <input type="text" onkeydown="if(event.keyCode===13) sendDanmuCanvas()">
    <button onclick="sendDanmuCanvas()">发送</button>
    <canvas></canvas>
    <script>
      let canvas = createCanvas();
      let danmus = [];
      /**
       * [createCanvas 创建画布]
       * @return {[object]} [canvas对象]
       */
      function createCanvas() {
        // 创建canvas节点
        const canvas = document.createElement('canvas');
        // 设置canvas宽高和样式
        canvas.setAttribute('width', window.innerWidth);
        canvas.setAttribute('height', window.innerHeight);
        canvas.style.position = 'fixed';
        canvas.style.top = '0';
        canvas.style.left = '0';
        canvas.style.zIndex = '100';
        // 将canvas节点插入到DOM中
        document.body.appendChild(canvas);
        // 返回canvas对象
        return canvas;
      }

      /**
       * [removeDanmu 删除弹幕]
       * @param  {[object]} danmu [弹幕对象]
       */
      function removeDanmu(danmu) {
        danmus.splice(danmus.indexOf(danmu), 1);
      }

      /**
       * [danmuCanvas 动态弹幕画布]
       * @param  {[string]} text  [文字]
       * @param  {[number]} size  [文字大小]
       * @param  {[string]} color [文字颜色]
       */
      function danmuCanvas(text, size, color) {
        this.text = text;
        this.size = size;
        this.color = color;
        // 获取canvas窗口宽度和高度
        const canvasWidth = canvas.width;
        const canvasHeight = canvas.height;
        // 设置初始位置
        this.x = canvasWidth;
        this.y = Math.floor(Math.random() * (canvasHeight - size));
        // 设置弹幕移动速度,移动速度越快表示飞的越快
        const speed = Math.floor(Math.random() * 10 + 5);
        // 绘制弹幕
        this.draw = function() {
          // 获取canvas上下文
          const context = canvas.getContext('2d');
          // 设置字体大小和颜色
          context.font = size + 'px sans-serif';
          context.fillStyle = color;
          // 绘制弹幕文字
          context.fillText(text, this.x, this.y);
        };
        // 更新弹幕位置
        this.update = function() {
          this.x -= speed;
          // 判断弹幕是否超出屏幕
          if (this.x < -canvasWidth) {
            removeDanmu(this);
          }
        };
      }

      /**
       * [sendDanmuCanvas 发送弹幕画布]
       * @return {[type]} [description]
       */
      function sendDanmuCanvas() {
        // 获取input框
        const input = document.querySelector('input');
        // 获取input框中的value值
        const text = input.value;
        // 清空input框中的value值
        input.value = '';
        // 随机设置文字大小和颜色
        const size = Math.floor(Math.random() * 40 + 20);
        const color = `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`;
        // 创建一条弹幕
        const danmu = new danmuCanvas(text, size, color);
        // 将弹幕放入弹幕数组中
        danmus.push(danmu);
      }

      /**
       * [drawDanmuCanvas 绘制弹幕画布]
       */
      function drawDanmuCanvas() {
        // 获取canvas上下文
        const context = canvas.getContext('2d');
        // 清空画布
        context.clearRect(0, 0, canvas.width, canvas.height);
        // 绘制所有弹幕
        danmus.forEach((danmu) => {
          danmu.draw();
          danmu.update();
        });
        // 将所有弹幕更新后,延迟一段时间后再次调用该函数
        setTimeout(drawDanmuCanvas, 16);
      }
      // 调用drawDanmuCanvas函数,开始绘制弹幕画布
      drawDanmuCanvas();
    </script>
  </body>
</html>

4. 结语

通过以上两个版本的实现方式,我们可以更好地理解和使用JavaScript实现弹幕效果的相关方法。不同的实现方法适用于不同的场景,我们可以根据实际需求选择合适的技术实现。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:javascript实现视频弹幕效果(两个版本) - Python技术站

(0)
上一篇 2023年6月10日
下一篇 2023年6月10日

相关文章

  • Vue 项目迁移 React 路由部分经验分享

    下面详细讲解“Vue 项目迁移 React 路由部分经验分享”的完整攻略。 背景 在项目开发中,React 和 Vue 是两个非常常用的框架,在实际开发中,可能需要将一个 Vue 项目迁移到 React 项目中,其中涉及到路由部分,如何进行迁移呢?下面给出一些经验分享。 步骤 确定 React 项目结构 建议先熟悉一下 React 项目的结构,确定 Reac…

    JavaScript 2023年6月11日
    00
  • JS幻想 读取二进制文件第2/2页

    浏览器中读取二进制文件需要使用 FileReader 和 Blob 对象。下面介绍一下具体的操作步骤。 步骤一:获取文件 通过文件选择器或者其他方式获取二进制文件的实例。可以使用 <input> 标签加上 accept 属性来实现文件选择器。 <input type="file" accept=".bin&qu…

    JavaScript 2023年5月27日
    00
  • 浅谈两种前端截图方式:Canvas截图 vs SVG截图

    背景 如今很多网站都引入截图功能,可用于问题反馈、内容分享等实用需求,而前端截图也不知不觉成为了首选。今天为大家推荐两种前端截图方式,虽然有些局限,但是也能应付大部分项目需求。 Canvas截图:html2canvas SVG截图:rasterizehtml 原理 首先来谈下两种前端截图方式的原理,虽然实现方式不太一致,但是核心思想是相同的。 以html2c…

    JavaScript 2023年4月18日
    00
  • android WebView加载html5介绍

    下面我将为您详细讲解android WebView加载html5的攻略。 简介 WebView是Android提供的一个用于显示网页的控件,其底层使用的是Chrome浏览器内核,因此支持HTML5技术。HTML5是一种用于Web开发的标准,增加了很多新的功能,如音视频播放、Canvas绘图、自适应布局等。本文将介绍如何使用WebView来加载HTML5页面。…

    JavaScript 2023年6月11日
    00
  • javaScript合并对象的多种方式及知识扩展

    JavaScript合并对象的多种方式及知识扩展 什么是对象合并 在JavaScript中,合并对象指的是将多个对象中的属性和方法,合并成一个新的对象。这在实际应用中非常常见,特别是在处理大型复杂对象时,为了防止属性名冲突或简化处理逻辑,我们经常需要将多个对象合并成一个对象。 合并对象的多种方式 方法一:Object.assign Object.assign…

    JavaScript 2023年5月27日
    00
  • 一文教你如何实现localStorage的过期机制

    首先需要明确 localStorage 是HTML5标准中的一种客户端存储方式,可以在浏览器中存储数据并保留在客户端本地。而过期机制则是指设置一个过期时长,在达到时限之后,数据自动失效并被清空。 下面就来介绍如何实现 localStorage 的过期机制: 步骤1:封装localStorage 首先我们需要进行封装 localStorage,以方便我们在任何…

    JavaScript 2023年6月11日
    00
  • 一个不错的用JavaScript实现的UBB编码函数

    这里给出一个实现UBB编码的JavaScript函数的攻略。 函数功能 该函数可以将一段包含UBB语法的文本编码成HTML格式的文本。 实现思路 实现该函数需要分析包含UBB语法的文本,将其中的UBB语法转换为对应的HTML语法,最终生成HTML格式的文本。具体实现需要用到正则表达式、字符串替换等技巧。 具体步骤 定义一个函数,此函数接收一个包含UBB语法的…

    JavaScript 2023年5月20日
    00
  • js防抖-节流函数的基本实现和补充详解

    JS防抖和节流函数的基本实现和补充详解 在Web应用中,为了提升用户体验及减轻服务器压力,我们通常会使用JS防抖和节流函数来控制代码执行的频率及节约资源的使用。本文将对JS防抖和节流函数的基本实现进行详细的讲解,同时也会补充一些重要的知识点。 JS防抖函数的基本实现 JS防抖函数的原理是将多次触发的事件合并为一次触发,从而减少触发事件的次数,提高代码性能。比…

    JavaScript 2023年6月11日
    00
合作推广
合作推广
分享本页
返回顶部