views:

68

answers:

1

I'm building a website photo gallery for a friend. Images are loaded as simple DOM image objects (<img src="" />), and the size of these images is based on the browser size. So I resize them with CSS.

This isn't an optimal solution since CSS resizing seems to change the quality of the image and pixelate it quite a bit. I was thinking of rendering the image with canvas and then resize it with that so that the quality remains effective, but I can't find any info about this online.

Any ideas?

+1  A: 

Something like this:

<html>
<head>
<script type="text/javascript">

function init(){
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    var image = new Image();
    image.onload = function(){
       ctx.drawImage(image, x, y, width, height);
    };

    image.src = "filename.jpg";
}
</script>
</head>
<body onload="init()">
<canvas id="canvas" width="640" height="480"></canvas>
</body>
</html>

Probably the best resource: https://developer.mozilla.org/en/Canvas_tutorial/Using_images

Btw: You might run in to cross domain issues when loading an image. I think in Firefox the error is something like NS_SECURITY blah blah blah.. just make sure that your page and the image are coming from the same place. You might have to use a web server to test develop. Alternatively when developing in Firefox you can place this in your JavaScript to ignore these security restrictions: netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); Remember to remove that before deploying because this will break your code in every other browser.

Ronald