vue项目video、img配合canvas截图及资源跨域处理
[解决] VUE项目video、img截图及资源跨域处理视频截图视频截图代码如下:<template><div class="info"><videocrossOrigin="anonymous" // 1.跨域处理 [crossOrigin](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/c
视频截图
代码如下:
<template>
<div class="info">
<video
crossOrigin="anonymous" // 1.跨域处理 [crossOrigin](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin)
style="width:653px;height:354px;"
id="videoElement"
controls="controls"
autoplay
>
<source :src="dealVideoUrl" type="video/mp4">
</video>
<div class="cut" @click="toCut">存档</div>
</div>
</template>
<script>
export default {
name: 'info-approval',
components: {
},
data () {
return {
videoUrl: ''
}
},
computed: {
// 2.防止命中缓存
dealVideoUrl () {
return this.videoUrl + '?time=' + new Date().valueOf()
}
},
watch: {
// 防止命中缓存
saveUrl (src) {
return src + '?time=' + new Date().valueOf()
}
},
created () {
},
mounted () {
},
methods: {
// 截图
toCut () {
var video = document.getElementById("videoElement"); //获取前台要截图的video对象
video.setAttribute('crossOrigin', 'anonymous') // 跨域处理
var canvas = window.canvas = document.createElement("canvas");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height); // 将当前视频图片渲染在画布上,图片大小和视频分辨率一致
var images = canvas.toDataURL("image/png"); //canvas的api中的toDataURL()保存图像[toDataUrl](https://developer.cdn.mozilla.net/zh-CN/docs/Web/API/HTMLCanvasElement/toDataURL)
this.videoUrl= images
}
}
}
</script>
跨域处理
跨域图片、视频能正常裁剪(图片未转化成base64),应该满足三个条件:
1、img元素中设置crossorigin属性
2、图片允许跨域,设置响应头Access-Control-Allow-Origin
3、使用js方式请求图片资源, 需要避免使用缓存,设置url后加上时间戳,或者http头设置Cache-Control为no-cache
主要原因是:
如果使用跨域的资源画到canvas中,并且资源没有使用CORS去请求,canvas会被认为是被污染了, canvas可以正常展示,但是没办法使用toDataURL()或者toBlob()导出数据,见Allowing cross-origin use of images and canvas。 所以通过在img标签上设置crossorigin,启用CORS,属性值为anonymous,在CORS请求时不会发送认证信息,见HTML attribute: crossorigin。
在启用CORS请求跨域资源时,资源必须允许跨域,才能正常返回,最简单的方式设置响应头Access-Control-Allow-Origin: *
图片已经通过img标签加载过,浏览器默认会缓存下来,下次使用js方式再去请求,直接返回缓存的图片,如果缓存中的图片不是通过CORS请求或者响应头中不存在Access-Control-Allow-Origin,都会导致报错。
更多推荐
所有评论(0)