View Full Version : How to overlay images in javascript?

06-24-2010, 02:30 PM

I need to solve the following problem.

I have two (or more) .PNG images of the same dimensions. Each PNG image is created with transparent background color.

I need to display img1 and upon it img2, so in places where img2 has trancparent color, img1 will be seen.

For example: img1 upper part filled with transparent color and a cow on down part. img2 upper part contains clouds and downpart filled with transparent color.

I want to combine these two images and see clouds above the cow.

I understand that I need to use some filter when displaying both images, but not sure which one and what parameters of it to use.

Thanks in advance...

06-24-2010, 04:12 PM
You don't need a filter unless the transparency is alpha transparency (actually called alpha opacity) and the browser is IE 6 or less. Even with a filter in IE 6 and less, there might not be any way to overlay the two images in the way you describe. However, if the transparency is single color transparency and they are saved in 256 colors or less, no filter is needed in IE 6 and less and they can easily be overlaid. All other browsers will display alpha opacity .png images just fine with no added filter and they can easily be overlaid. Say the images are 150x300:

<div style="position: relative; width: 150px; height: 300px;">
<img src="img1.png" alt="" style="position: absolute; top: 0; left: 0;">
<img src="img2.png" alt="" style="position: absolute; top: 0; left: 0;">

No javascript required. If you want to start out with the images separate and/or unseen, javascript may be used to move them around and/or reveal them. But I would need more specifics on just how you want that to happen in order to provide javascript code for that.

06-25-2010, 09:02 AM
Thanks you, it worked once I changed my images to be 256 color (id didn't work for true color images).

Is there a possibility to use image overlaying for true color images?

(In IE6, IE7)?

06-25-2010, 04:54 PM
IE 7 - no problem. In IE 6 you need the alpha image loader filter:


But you may be able to use something like iepngfix:


which many people find easier to deal with. It uses the filter, but does a lot of the work for you.

The problem is that when one of these images overlays another, since the filter works by making the image a sort of super background image, it might not work out, but it may.

If you want more help:

Please post a link to your page.