Saturday, May 19, 2007

Using CSS to clip image with the help of jQuery

Last week I was reading a nice article by Seifi explaining how to clip an image in a web page by using available CSS techniques. I did like the idea of clipping images. Sometime there is no need to show the whole image on a page, especially if you want to save space.

Although the idea of clipping images interested me, the wholeprocess of getting an image chopped scared me, especially if you need to have different clippings on different sizes. Why calculate offsets and sizes manually if there is a computer which can do this for you. To accomplish this, I took the method in the article as a base and with the help of my favorite javascript framework jQuery, I got it all automated.

How?

In order to get the process of clipping images automated, some parameters are necessary to get the job done. These parameters are: size of original image, clipping offset and clipped size. I have chosen to use attributes on the img tag, allowing setting these values during design of the page.

Example

<img src="castle.jpg" id="clipit" alt="Clipped castle image" width="300" height="225" clipwidth="136" clipheight="105" clipleft="82" cliptop="50" />


As you can see, I have used some custom properties to the img tag, which will be used by javascript during the clipping process. In order to get the image clipped I have written a javascript function which can be called.

clipImage( 'id-of-image', 1);


This function will take care of it all and it will render the clipped image with the given parameters. I didnt spend much time on the code and it is quick and dirty. Maybe it would be an idea create a jQuery plugin for it.

Demo

The demo page showing the image clipping can be found here.
Please look at the source to see the implementation.


Feedback/Comments

If you have any questions or remarks about this code, you can always contact me.


No comments: