Stretching a Backgound Image using JavaScript and CSS
13:45.22 - Monday 14th August 2006 (Link to This Entry)
UPDATE:
Thanks to viveka for pointing out that this code didn't actually work - I've fixed the two stupid buglets and tested it and it does now. Apologies all round!
Anyway, previously...
--------
I put a rather nice website design together a week or so back for a prospective client which used something I had never attempted before - a background image that is scaled to cover the whole page, no matter what dimensions the browser window is resized to. All well and good, but it turns out we got the job and I had to actually implement the bloody thing.
First up, we don't actually use the BODY to display our background image, but a DIV (ID=bg, below) with WIDTH and HEIGHT set to 100% so it always covers our entire document display. To prevent scrollbars appearing on these elements we hide the overflow on them, so our main document looks like this:
<BODY STYLE="overflow:hidden;" onResize="imgResize();" onLoad="imgResize();"> <DIV ID="bg" STYLE="position:absolute; overflow:hidden; top:0px; left:0px; width;100%; height:100%;"> <IMG SRC="test.jpg" WIDTH="800" HEIGHT="600" BORDER="0" ID="bgImage"> </DIV> <DIV ID="fg" STYLE="position:absolute; top:0px; left:0px; width:100%; height:100%; overflow:auto;"> Content in Here! </DIV> </BODY>The content actually sits in another DIV (ID=fg,above) with it's overflow forced to 'auto' so that we always see the space for a scrollbar, even if there's nothing to do with it, and it resembles a regular browser window as closely as possible.
This setup allows us to access the image using getElementById and control it's width and height according to our requirements. Naturally this requires some JavaScript:
<SCRIPT language="JavaScript" TYPE="TEXT/JAVASCRIPT"> var winWidth=0; var winHeight=0; var imgWidth=800 var imgHeight=600 var newWidth=0; var newHeight=0;There's some aspect-ratio related checks in the JavaScript to ensure your background image doesn't get stretched out of shape as well. With some experimentation I've found that a background image of 800x600 gives great results at pretty much all sizes and isn't too big - a nice balance between image quality and file size.
function imgResize() { var bgImage=document.getElementById('bgImage'); if(window.innerWidth) { winWidth =window.innerWidth; winHeight=window.innerHeight; } else { winWidth=document.body.offsetWidth; winHeight=document.body.offsetHeight; } if(winHeight>imgHeight) { newHeight=winHeight; newWidth=winHeight*(imgWidth/imgHeight); } if(newWidth<winWidth) { newWidth=winWidth; newHeight=newWidth*(imgHeight/imgWidth); } bgImage.style.width =newWidth; bgImage.style.height=newHeight; } </SCRIPT>
