canvas对视频截图报错:Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement'

  • 需求

页面加载完成后,视频如果没有封面图,使用canvas对视频截图作为封面图,并且通过接口传回保存。

  • 实现

canvas对视频截图,十分简单,只需几行代码。

  1. 获取页面中的video
let video = document.getElementById('video');
  1. 创建canvas并设置画布长和宽
let canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
  1. 绘制
let ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  1. 获取图片数据
let dataURI = canvas.toDataURL('image/jpeg');

这里会得到图片的base64数据。但就在这里出现了错误:

Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

这是因为video的资源地址与当前页面是跨域状态,只需要在video中添加属性:

crossorigin="anonymous"