大家好!
我正在尝试制作一个演示,用户可以通过浏览器启用网络摄像头来捕获图像,并使用AJAX调用将此图像传递给PHP服务端以保存。
我能够捕获画布,但无法将其转换为图像数据。我得到了“canvas未定义错误”的提示。
设置非常简单。
HTML
<video id="videoElement" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" style="display:none" ></canvas>
JAVASCRIPT
// Grab elements, create settings, etc.
var video = document.getElementById('videoElement');
// Get access to the camera!
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// Not adding `{ audio: true }` since we only want video now
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
});
}
// Elements for taking the snapshot
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('videoElement');
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
var cann= context.drawImage(video, 0, 0, 640, 480); //draw canvas
//then convert canvas to image so i can obtain dataurl
//and pass it to another function using AJAX
var img= convertCanvasToImage(cann);
console.log(img);
});
// Converts canvas to an image
function convertCanvasToImage(canvas)
{
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
我在这个领域还比较新,还有一个问题。最新版本的浏览器能否支持这个?有人能帮我找出我所犯的错误吗?