我正在尝试将图像从网络摄像头保存为文件,然后将其加载为背景图像(每当按下按钮时)。但是,当我按下按钮时,我的文件发生了变化,但背景图像(在画布上)保持不变。所以背景图像总是第一个快照图像。当我清除缓存我的背景图像在画布上设置为最新文件。有什么问题?
的index.html
<button id ="snap">Snap Photo</button><br>
<canvas id ="canvas" width="800" height="500"></canvas>
<video id = "video" width="640" height="480" autoplay></video>
<script type="text/javascript" src="file.js"></script>
file.js
window.onload = function() {
backgroundImage = null;
// Grab elements, create settings, etc.
var video = document.getElementById('video');
// 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();
});
}
//get canvas and context element
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
ctx.drawImage(video, 0, 0);
var canvasData = c.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);
backgroundImage = new Image();
backgroundImage.src = "test.png";
});
//call update function every 80 nanoseconds
setInterval(function() {
update(c, ctx);
}, 80);
}
function update(c, ctx) {
//draw backgroundImage
if (backgroundImage) {
ctx.drawImage(backgroundImage, 0, 0, 640, 480);
}
}
testSave.php
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>