PDA

View Full Version : tutorial: Getting more quality out of small images using the canvas


gabrielcrowe
30-Aug-2007, 02:13 PM
Firefox and Internet explorer 7 include a javascript concept, known as the canvas.

at its heart, the canvas is an object that you can draw shapes and manipulate using javascript. in this example, i'll show you how to use the canvas to scale an image, in a much prettier way than a browser does.

first example 'canvas.html':
<html>
<head>

</head>
<body>

<canvas id="canvas" width="600" height="600"></canvas>
<img src="test.jpg" width="600" height="600">

<script type="application/x-javascript">
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = 'test.jpg';
img.onload = function(){
ctx.drawImage(img,0,0,document.getElementById('canvas').width,document.getElementById('canvas').height);
}
</script>


</body>
</html>

attached is a jpg, to test with. chuck them both in the same folder, and then open this html file in firefox

what is happening?

well, the first image, shows the image strehed using the javascript canvas, with basic smoothing.

the second image, shows what a browser does, when you change the dimensions of the image, see the ugly pixelling in the right image?

well, have fun with that example. i do home that someone can put it to good use. the canvas is a very powerful tool.

look at this for a great example of it put to good use:

http://cow.neondragon.net/stuff/reflection/
http://www.netzgesta.de/cvi/
http://developer.mozilla.org/en/docs/Drawing_Graphics_with_Canvas

JSnow
30-Aug-2007, 02:30 PM
Awesome! Nice one govener.