Saturday, August 15, 2009

Auto-resizing background image

JQuery: I found a very nice jQuery plugin called Supersized that makes it very easy to add an auto-resizing background image to your website. And it includes a slideshow function!

Canvas: I recently started to teach myself how to use Canvas and I thought, hey.. I bet I could do that with canvas too! For those of you that don't know, you can easily draw (graphs), resize and rotate images with canvas. Here is a very nice demo of image manipulation.

So, I'm pretty sure this is an un-approved method of using canvas as it's meant for smaller sized images. But it works! :P Well, it works for all current browsers, except IE - you'll need this plugin called ExploreCanvas to make it work.
<canvas id="myCanvas" style="width: 100%; height: 100%; position: absolute; left: 0px; top: 0px; z-index: -1;"></canvas>
<script type="text/javascript">
var elem = document.getElementById('myCanvas');
var context = elem.getContext('2d');
var w = document.body.clientWidth;
var h = document.body.clientHeight;
img = new Image();
img.src='http://i201.photobucket.com/albums/aa236/Mottie1/testsite/screenshots/bg1.jpg';
img.onload = function () {
context.drawImage(this,0,0,300,150);
};
</script>
*Note* The drawImage function of canvas needs to be 300 x 150 for this script as that is the default canvas size, which then gets stretched to 100% width and height using the CSS.

And the problem I discovered with both the jQuery plugin and the canvas script above is that you are limited to the content on the screen. Should you need to scroll the page down, the image scrolls up (I had to modify the jQuery plugin to discover that).

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.