我使用HTML5相机拍照。我注意到,在拍摄完照片后,虽然我对视频和画布应用了相同的宽度和高度,但最终的图像宽度和高度都会拉长。
请参阅此JSFIDDLE
var video = document.querySelector("#videoElement");
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true}, handleVideo, videoError);
}
function handleVideo(stream) {
video.src = window.URL.createObjectURL(stream);
}
function videoError(e) {
// do something
}
var v,canvas,context,w,h;
var imgtag = document.getElementById('imgtag');
var sel = document.getElementById('fileselect');
//document.addEventListener('DOMContentLoaded', function(){
v = document.getElementById('videoElement');
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
w = canvas.width;
h = canvas.height;
//},false);
function draw(v,c,w,h) {
if(v.paused || v.ended) return false;
context.drawImage(v,0,0,w,h);
var uri = canvas.toDataURL("image/png");
imgtag.src = uri;
}
document.getElementById('save').addEventListener('click',function(e){
draw(v,context,w,h);
});
var fr;
sel.addEventListener('change',function(e){
var f = sel.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsDataURL(f);
})
function receivedText() {
imgtag.src = fr.result;
}
答案 0 :(得分:1)
您的代码包含视频和画布元素的宽度和高度的硬编码值。
避免在两个方向上设置绝对大小,因为视频元素的尺寸可能会有所不同。您可以仅使用宽度或仅使用高度或使用CSS样式/规则来设置大小。
对于画布,您需要根据视频元素的实际大小设置大小。为此,请使用视频元素属性:
video.videoWidth;
video.videoHeight;
您可以根据需要应用缩放,例如:
scale = 300 / v.videoWidth;
w = v.videoWidth * scale;
h = v.videoHeight * scale;
canvas.width = w;
canvas.height = h;
context.drawImage(v, 0, 0, w, h);
<强> Updated fiddle 强>