Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

video 截图开发 #9

Open
yandeqiang opened this issue Dec 14, 2017 · 0 comments
Open

video 截图开发 #9

yandeqiang opened this issue Dec 14, 2017 · 0 comments

Comments

@yandeqiang
Copy link
Owner

video 截图

预期:将 video 当前桢的画面数据拿出来

技术方案:

在做 video 移动端兼容性的时候, 就有大神提出来,用 canvas 来绘制 video 的 hack 方案。

canvas 还提供了,两个可以把图像数据取出来的 api:

canvas.toDataURL()

Canvas.toBlob()

实现:

html:

<video src="http://yunxianchang.live.ujne7.com/vod-system-bj/103_371ab0c0fda-143d-4755-8727-d3cd12dce02d.mp4" controls></video>

js:

const canvas = document.createElement('canvas');

// 得设置高度,不然会采用默认宽高 300 * 150
canvas.width = 1080;
canvas.height = 607;

const ctx = canvas.getContext('2d');

ctx.drawImage(document.querySelector('video'), 0, 0);
document.documentElement.appendChild(canvas);
console.log(canvas.toDataURL());

然而: 尽然报错

Google 下, 发现是,跨域的问题导致的

mdn 的一个解释:

What is a "tainted" canvas?

Although you can use images without CORS approval in your canvas, doing so taints the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; doing so will throw a security error.

This protects users from having private data exposed by using images to pull information from remote web sites without permission.

总结一下:为了保护用户的数据隐私,做了一个“残缺”的 canvas api。当图片源是有跨域问题的时候,toBlob(), toDataURL(), getImageData() 这三个方法报安全错误。

当然也有解决方案

mdn 提供的:

In HTML5, some HTML elements which provide support for CORS, such as img, video or script, have a crossorigin attribute (crossOrigin property), which lets you configure the CORS requests for the element's fetched data. These attributes are enumerated, and have the following possible values:

Keyword Description
anonymous CORS requests for this element will not have the credentials flag set.
use-credentials CORS requests for this element will have the credentials flag set; this means the request will provide credentials.

总结一下 :可以设置 cors 头,来规避这个安全问题

最后:

<video crossorigin="anonymous" src="http://yunxianchang.live.ujne7.com/vod-system-bj/103_371ab0c0fda-143d-4755-8727-d3cd12dce02d.mp4" controls></video>

不过我突然有些疑问, 既然这个参数也可以动态添加,那个增加这个安全设置的意义在哪?有知道的同学可以回答讨论下。

参考

  1. image 跨域访问代码求解释
  2. CORS enabled image
  3. [CORS settings attributes](CORS settings attributes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant