安卓很多浏览器播放视频都会新开窗口,甚至播放完毕会有类似播放器的那种推荐广告,让我很是头疼。我一度以为用canvas绘制视频,应该可以解决这个问题,但是当我用canvas绘制完了视频之后,在微信中播放还是一样弹出新的播放窗口!!这就是移动端video视频播放的痛!
失败案例一
也就是我目前邀请函用的方式,因为我用canvas绘制了video,发现效果和直接用video一样。因此还是用了原来video的方式,代码如下:
<div class="commondw videoimg" id="videoimg"></div>
<video class="vido" id="vidoid" poster="images/photo/video.jpg">
<source src="media/move.mp4" type="video/mp4">
</video>
$("#videoimg").on("click", function () {
$(this).fadeOut(1000);
$(".clicktips").hide();
$("#vidoid").show();
$("#vidoid")[0].play();
$("#vidoid").bind('ended', function () {
$("#vidoid").hide();
$("#videoimg").show();
})
});
失败案例二(canvas渲染video)
后来我想到用canvas渲染video,也就是通过canvas的drawImage方式,结合requestAnimationFrame动画。
下面贴出代码
function VideoToCanvas(videoElement,fn) {
if (!videoElement) {
return;
}
var fn=fn||"";
var canvas = document.createElement('canvas');
canvas.width = videoElement.offsetWidth;
canvas.height = videoElement.offsetHeight;
var ctx = canvas.getContext('2d');
var newVideo = videoElement.cloneNode(false);
var timer = null;
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
function drawCanvas() {
ctx.drawImage(newVideo, 0, 0, canvas.width, canvas.height);
timer = requestAnimationFrame(drawCanvas);
}
function stopDrawing() {
cancelAnimationFrame(timer);
}
function endedCallBack(){
cancelAnimationFrame(timer);
fn && fn()
}
newVideo.addEventListener('play', function () {
drawCanvas();
}, false);
newVideo.addEventListener('pause', stopDrawing, false);
newVideo.addEventListener('ended', endedCallBack, false);
videoElement.parentNode.replaceChild(canvas, videoElement);
this.play = function () {
newVideo.play();
};
this.pause = function () {
newVideo.pause();
};
this.playPause = function () {
if (newVideo.paused) {
this.play();
} else {
this.pause();
}
};
this.change = function (src) {
if (!src) {
return;
}
newVideo.src = src;
};
this.drawFrame = drawCanvas;
this.show = function () {
canvas.style.display = "block";
}
this.hide = function () {
canvas.style.display = "none";
}
}
封装了显示show()、隐藏hide()、播放play()、暂停pause()、更换地址change()以及切换播放和暂停playPause();
使用方法如下:
var canvasvedio=new VideoToCanvas(document.getElementById("vidoid"),function(){
canvasvedio.hide();
$("#videoimg").show();
});
canvasvedio.play();
还有一个回调函数,就是在canvas播放完毕之后,可以传入回调函数!但是在安卓的微信、和一些浏览器中还是会弹出新的窗口,很是郁闷!!
深圳 · 龙岗 · 大运软件小镇22栋201
电话:400 182 8580
邮箱:szhulian@qq.com