【问题标题】:Set video poster [duplicate]设置视频海报 [重复]
【发布时间】:2022-02-02 08:21:06
【问题描述】:

我有这段代码 =>

<video id="video" class="video-js vjs-default-skin" controls preload="auto" width="640" height="268" data-setup='{ "playbackRates": [0.5, 1, 1.5, 2],"loopbutton": true  }'>
    <source src="http://vjs.zencdn.net/v/oceans.mp4" type='video/mp4'>
</video>

<canvas id="canvas" style="width: 640px !important; height: 268px !important"></canvas>

这是我的 JS =>

var canvas = document.getElementById('canvas');
var video = document.getElementById("video"); 
var cw = canvas.width = 200;
var ch = canvas.height = Math.round(cw / 1.7777);

function genT() {     
    var context = canvas.getContext('2d');
    context.drawImage(video, 0, 0, cw, ch);
    document.getElementById("video_html5_api").setAttribute("poster", canvas.toDataURL());
    //console.log(canvas.toDataURL()); //debug
}

video.addEventListener('pause', function() {
   genT();
});

每次我暂停视频时,我都想将视频海报更改为视频暂停的帧,一切正常,但我无法设置视频海报。这是错误 => Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

@edit:我不是从外部带来图像,而是从我的视频中“创建”图像,所以当我搜索此内容时,我不了解 CORS 政策。

我该如何解决这个问题?谢谢

【问题讨论】:

  • 您的视频是“来自外部”,这就是触发跨域污染的原因。

标签: javascript html canvas


【解决方案1】:

您遇到了 CORS 问题。

MDN Docs
跨域资源共享 (CORS) 是一种基于 HTTP 标头的机制,它允许服务器指示浏览器应允许从其加载资源的任何来源(域、方案或端口)。

该文件来自另一个启用了 CORS 的服务器,或者来自file:///,出于安全原因,不允许这样做。

基本上,
远程服务器应提供具有以下标头的文件:

Access-Control-Allow-Origin "*"

您可以通过将此行添加到您的 JS 文件中来访问它:

video.crossOrigin = "anonymous";

或使用 HTML 属性

<!-- Distant server allows CORS -->
<video crossorigin="anonymous" ...

但是,如果该标题不存在 - 你就不走运了。

更多信息:

【讨论】:

  • 你可以“画”它,你不能背诵。
猜你喜欢
  • 1970-01-01
  • 2017-07-25
  • 2016-01-16
  • 2020-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 1970-01-01
相关资源
最近更新 更多