Streamed web images without flickering
Overview
Putting a stream of images on the web, like from a camera, can be painful. Constantly refreshing the page with a meta tag causes flickering, DOM modification requires busting the cache, and without the cache you again get flickering on the image.
Code
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function upd(count)
{
$("#capImg").html(
'<img width=384px height=288px src="foo.jpg?' +
count + '">');
count ++;
$("#capImgHidden").html(
'<img width=1px height=1px src="foo.jpg?' +
count + '">');
setTimeout("upd(" + count + ");",500);
}
setTimeout("upd(0);",500);
</script>
<html>
<head>
<title>Image Stream</title>
</head>
<body>
<div id="capImg">
<img src="foo.jpg">
</div>
<BR>
<div id="capImgHidden" style:display="none">
<img width=1 height=1 src="foo.jpg?0">
</div>
</body>
</html>
Explanation
- jQuery is used to modify the html on in the javascript. This is done every 500 milliseconds using setTimeout.
- Each call of the upd function has count incremented by one each time. This is then used as part of the image location (foo.jpg?0, foo.jpg?1, foo.jpg?2), making the browser think each one is a separate location and thus bypassing the cache. We are passing in the number as a GET parameter, which is discarded at the server side since foo.jpg is just a normal image and does not take parameters.
- Since we've busted the cache, the browser downloads a fresh copy of the image each time. The time it takes to do that causes flickering. The trick is to load the image with the same name in a hidden area, which is just a 1x1 image (capImgHidden). For example:
- Display foo.jpg?0, hide foo.jpg?1
- Display foo.jpg?1, hide foo.jpg?2
- Display foo.jpg?2, hide foo.jpg?3
- ...
Conclusion
Works well, and isn't that complicated to implement. Really fast rates (Under 100ms on my machine) will still cause flickering even with caching. Also the data source can produce it's own issues, such as slow writing of files resulting in corrupted images being retrieved.
Comments(0)
2010-01-27 03:15:37