在画布上渲染视频元素时,我无法按比例缩放视频帧.
我阅读了如何在画布中按比例调整图像大小的选定答案?但它对我不起作用.我正在渲染HTML5视频帧而不是图像.这可能看起来很不寻常,所以在这里解释:视频+画布=魔术
我对调整相关问题的答案的问题可能是:
现在,我的播放器工作,将视频适合它,但它延伸到适合.
context.drawImage(videoPlayer, 0, 0, canvasPlayer.width, canvasPlayer.height);
//canvasPlayer -> HTML5 canvas, videoPlayer -> HTML5 video element
Run Code Online (Sandbox Code Playgroud)
我想(分别)知道:
如何垂直填充高度,保持比例.
如何水平填充宽度,保持比例.
我怎样才能做到这一点?
这是一种将视频按比例绘制到画布中的方法(保持纵横比):
// var c = canvasElement, v=videoElement;
// fill vertically
var vRatio = (c.height / v.videoHeight) * v.videoWidth;
ctx.drawImage(v, 0,0, vRatio, c.height);
// fill horizontally
var hRatio = (c.width / v.videoWidth) * v.videoHeight;
ctx.drawImage(v, 0,0, c.width, hRatio);
Run Code Online (Sandbox Code Playgroud)
// var c = canvasElement, v=videoElement;
// fill vertically
var vRatio = (c.height / v.videoHeight) * v.videoWidth;
ctx.drawImage(v, 0,0, vRatio, c.height);
// fill horizontally
var hRatio = (c.width / v.videoWidth) * v.videoHeight;
ctx.drawImage(v, 0,0, c.width, hRatio);
Run Code Online (Sandbox Code Playgroud)
function draw(){
// fill vertically
var vratio = (c.height / v.videoHeight) * v.videoWidth;
ctx.drawImage(v, 0,0, vratio, c.height);
// fill horizontally
var hratio = (c.width / v.videoWidth) * v.videoHeight;
ctx1.drawImage(v, 0,0, c1.width, hratio);
requestAnimationFrame(draw);
}
var c=document.createElement('canvas');
c.width = 640;
c.height= 480;
var ctx = c.getContext('2d')
var c1 = c.cloneNode(true);
var ctx1 = c1.getContext('2d')
var v = document.createElement('video');
v.controls=true;
document.body.appendChild(document.createTextNode('fill vertical\n'));
document.body.appendChild(c);
document.body.appendChild(document.createTextNode('fill horizontal\n'));
document.body.appendChild(c1);
document.body.appendChild(document.createTextNode('original'));
document.body.appendChild(v);
var anim;
v.onplaying = function(){
anim = requestAnimationFrame(draw);
};
v.onpause= function(){
cancelAnimationFrame(anim);
};
v.onloadedmetadata = function(){v.play();};
v.src = 'http://media.w3.org/2010/05/sintel/trailer.mp4';
var inputs = document.querySelectorAll('input');
inputs[0].addEventListener('change', inpHandler);
inputs[1].addEventListener('change', inpHandler);
function inpHandler(){
c[this.name]=this.value;
c1[this.name]=this.value;
v.currentTime=0;
v.play();
}Run Code Online (Sandbox Code Playgroud)
canvas{border:solid 1px;}
canvas,video{ display:block;}Run Code Online (Sandbox Code Playgroud)