I just implemented something similar. I have an IP webcam on my network, but I noticed that the built-in viewer uses 30% cpu time on my laptop when I view it in Chrome. (20% on Firefox, about the same on IE using an ActiveX version of the client.) The built-in viewer supports a 'cell phone' mode that sends a stream of jpegs, but in an awful way that uses even more cpu time. I decided to write my own wrapper around the url it uses to get a jpeg of the current camera view.
This uses requestAnimationFrame, and lets me set the max framerate I want. Since I'm just watching my dog Mischa and she sleeps most of the time, I set it to 0.5fps which keeps my cpu usage around 1%.
<div>
<img id="mischacam" />
<br />
<span id="time"/>
</div>
<script type="text/javascript">
var camURL = "....";
var msPerFrame = 2000;
var loading = false;
function update(timestamp) {
if (loading) return;
loading = true;
lastFrameTime = timestamp;
$("#mischacam").attr("src", camURL + "/snapshot.cgi?_=" + Math.random());
$("#time").html(new Date().toString());
}
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
var lastFrameTime;
function animloop(timestamp){
if (lastFrameTime == null) lastFrameTime = timestamp;
if (timestamp - lastFrameTime > msPerFrame)
update(timestamp);
requestAnimFrame(animloop);
}
$(document).ready(function () {
$("#mischacam").on("load", function () { loading = false; });
animloop(0);
});
</script>
mannix is right; to get the browser to reload the image I have to change the url every time. You'd think in a well-designed webcam API the image would come back with appropriate headers to prevent caching, but I didn't even bother to check. The webcam software is not well-designed.
This uses requestAnimationFrame, and lets me set the max framerate I want. Since I'm just watching my dog Mischa and she sleeps most of the time, I set it to 0.5fps which keeps my cpu usage around 1%.