如何使用外部视频画布?

时间:2014-07-24 17:54:46

标签: javascript html5 video canvas

我有以下代码:

<!DOCTYPE html> 
<title>Video/Canvas Gray Effect</title> 
<script> 
document.addEventListener('DOMContentLoaded', function(){
    var v = document.getElementById('v');
    var canvas = document.getElementById('c');
    var context = canvas.getContext('2d');
    var back = document.createElement('canvas');
    var backcontext = back.getContext('2d');

    var cw,ch;

    v.addEventListener('play', function(){
        cw = v.clientWidth;
        ch = v.clientHeight;
        canvas.width = cw;
        canvas.height = ch;
        back.width = cw;
        back.height = ch;
        draw(v,context,backcontext,cw,ch);
    },false);

},false);

function draw(v,c,bc,w,h) {
    if(v.paused || v.ended) return false;
    // First, draw it into the backing canvas
    bc.drawImage(v,0,0,w,h);
    // Grab the pixel data from the backing canvas
    var idata = bc.getImageData(0,0,w,h);
    var data = idata.data;
    // Loop through the pixels, turning them grayscale
    for(var i = 0; i < data.length; i+=4) {
        var r = data[i];
        var g = data[i+1];
        var b = data[i+2];
        var brightness = (3*r+4*g+b)>>>3;
        data[i] = brightness;
        data[i+1] = brightness;
        data[i+2] = brightness;
    }
    idata.data = data;
    // Draw the pixels onto the visible canvas
    c.putImageData(idata,0,0);
    // Start over!
    setTimeout(draw,20,v,c,bc,w,h);
}
</script> 



<video id=v controls loop> 
    <source src=video.webm type=video/webm> 
</video> 
<canvas id=c></canvas> 

<style> 
#c {
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -180px 0 0 20px;
}

#v {
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -180px 0 0 -500px;
}
</style>

只有在我的网站中托管视频时,画布才起作用,但如果外部视频中的画布不起作用,则只有在使用同一域创建代理时才会起作用,例如:

如果在我的网站上托管了视频,则工作:

   <video id=v controls loop> 
        <source src=video.webm type=video/webm> 
    </video>

使用代理时工作,但我不会使用代理:

<video id=v controls loop> 
        <source src=./proxy.php?url_toexternal_video=http://host.com/video.webm type=video/webm> 
    </video>

如果使用视频的直接链接,则无效:

<video id=v controls loop> 
        <source src=http://host.com/video.webm type=video/webm> 
</video>

如果来自外部视频,是否可以使其正常工作?谢谢! ;)

1 个答案:

答案 0 :(得分:0)

不,没有办法在被跨域内容污染的画布上使用getImageData