【问题标题】:Slitting HTML5 canvas (video) element into pieces将 HTML5 画布(视频)元素分割成小块
【发布时间】:2016-05-02 07:54:14
【问题描述】:

我是画布的新手,我已经在谷歌上搜索了几个小时,但我被卡住了。

我想做的是在画布元素上渲染视频,将其分割并为各个部分设置动画。我已经完成了一半(请参阅:http://jsbin.com/riduxadazi/edit?html,css,js,console,output)但我有几个问题:

  1. 我做的事情是对的,还是效率极低?
  2. 我想全屏使用视频。无论我尝试什么,画布网格 + 视频似乎都不匹配大小。
  3. 我想为视频片段制作动画,但我不知道应该如何处理它们。我可以得到某种数组并一个一个地为这些片段设置动画吗?

我的 JS 看起来像这样。我试图将 cmets 添加到最重要的部分。至少我认为是最重要的部分;)

var video = document.getElementById('video'); // Get the video
var ctx = canvas.getContext('2d'), 
    columns = 6,
    rows = 4,
    w, h, tileWidth, tileHeight;

// Start video and add it to canvas
video.addEventListener('play', function() {
    var $this = this; //cache
    (function loop() {
      if (!$this.paused && !$this.ended) {

        ctx.drawImage($this, 0, 0,window.innerWidth,window.innerHeight); 

        calcSize(); // Divide video

        setTimeout(loop, 1000 / 30); // drawing at 30fps
      }
    })();
  }, 0);  

function calcSize() {
    video.width = w = window.innerWidth;
    video.height = h = window.innerHeight;

    tileWidth = w / columns;
    tileHeight = h / rows;

    ctx.strokeStyle = '#000';

    render();
}
function render() {

    for(var x = 0; x < columns; x++) {
        ctx.moveTo(x * tileWidth, 0);
        ctx.lineTo(x * tileWidth, h);
    }
    for(var y = 0; y < rows; y++) {
        ctx.moveTo(0, y * tileHeight);
        ctx.lineTo(w, y * tileHeight);
    }
    ctx.stroke();
}

【问题讨论】:

  • 所以现在你只是在你的视频上画一个网格对吗?您必须使用单元格的坐标和 drawImage 的裁剪选项来实际分割您的视频。

标签: javascript jquery canvas html5-canvas html5-video


【解决方案1】:

你或许会考虑:

  • 使用requestAnimationFrame 更新循环。这允许与监视器更新速率完美同步,并且比 setTimeout/setInterval 更有效您可以限制它,以便您只更新每 1/30 帧以匹配视频速率,方法是使用交替的简单布尔标志。
  • 视频元素不需要插入到 DOM 中。此外,实际视频位图大小是通过属性videoWidthvideoHeight 读取的,但是,在提供的代码中,您应该使用画布的属性widthheight,因为这决定了目标大小。例如,要绘制比例,您可以使用 this answer
  • 如果您想分割内容,使用 drawImage() 和剪辑参数将是更有效的方式将视频绘制到画布上。
  • 您可以使用数学方法(请参阅 this answer)或使用允许您定义源区域并在其上具有单独属性(例如位置、旋转、缩放等)的对象来分割视频向前。如果您必须考虑采用当前画布大小的目标位置。

【讨论】:

    猜你喜欢
    • 2021-08-19
    • 2022-01-12
    • 2013-05-10
    • 2016-09-24
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2021-11-23
    • 2018-02-01
    相关资源
    最近更新 更多