Cross-browser Variable Opacity with png_ experience Exchange

Source: Internet
Author: User
Tags transparent color

Periodically, someone tells me about the magic of PNG, how it's the ideal image format for the web, and that someday we ' ll All is using it on our sites instead of GIF. People have been saying this to years, and by now most of us have stopped. Sadly, flaky browser support has made PNG impractical for almost everything; But now, with a few simple workarounds, we can finally put one of its most compelling features to use.

Png? What?

The Portable Network Graphics, or PNG (pronounced "ping"), image format has been around since, has 1995 up cropped ng the now Long-forgotten GIF scare, where Compuserve and Unisys announced they would begin charging for the The GIF image format.

To provide GIF support in their applications, software makers like Adobe and Macromedia must pay royalty fees–fees which are passed down to the "end" user in the selling cost of the software.

When PNG appeared on the scene, web designers were ready to make the "switch to" free, superior format and Shun GIF fore Ver. But over time, browsers continually failed to support PNG, and eventually most people to started about it. Today, nearly everyone still uses GIF habitually.

Which is a shame, because PNG makes GIF look pretty pathetic:it supports gamma correction, (sometimes) smaller file sizes , loss-less compression, up to 48-bit color, and, best of all, true alpha transparency.

To get why alpha transparency be a big deal, we must the understand most of

Binary transparency:the Scourge GIF

When it comes to transparency, GIF doesn ' t cut it. Whereas PNG supports alpha transparency, GIF only supports binary transparency, which are a big limitation and has a couple of important implications.

For one, an GIF image can either use no transparent colors in all or have one color that ' s completely transparent–there a Re no degrees of transparency.

And if a complex GIF does contain a transparent color, the background color of the Web page must match the transparent Col Or, or else the anti-aliased area around the transparent color is surrounded by ugly haloing and fringing. If you have ' ve spent more than five minutes as a web designer, you know what I ' m talking about.

The???? anti-aliased Transparent GIF is inextricably tied to the background color of the Web page on which It lives. If you are ever decide to change this color, you are must also change the GIF.

Miraculously, PNG doesn ' t behave that way. A PNG can is transparent in varying degrees–in the other words, it can is of variable opacity. And a transparent PNG is background-independent:it can live to any background color or image. Say you want your navigation in monkeys-run-amuck.com to is 65% opaque so can, through it to your orangutan und image. can do that. A Transparent anti-aliased "gorillas, chimps, Gibbons, et al" title that can sit on the top of any background color or image? Can do that, too.

So What about Browser Support?

By now, the course, we ' d all is up to our ears in PNGs if browsers supported them. But seven years after the format's inception, you still can ' t slap a PNG onto a Web page like you can a GIF or JPG. It ' s disgraceful, but as bad as it sounds.

It turns out this most of the latest versions of the major browsers fully the Alpha support with transparency, Ne Tscape 6, Opera 6, and recently-released Mozilla 1, all on Windows; And, for the Mac, Internet Explorer 5, Netscape 6, Opera 5, Mozilla 1, OmniWeb 3.1, and icab 1.9. Incredibly, PNG even works on Opera 6 for Linux, on WebTV, and on Sega Dreamcast.

Now, what ' s missing from that list?

Ie5.5+/win, bless its heart, 'll, in fact, display a PNG, but it doesn ' t natively support alpha transparency. In Ie5.5+/win, the transparent area of your PNG would display at 100% Opacity–that are, it won ' t be transparent to all .

Bugger. So what did we do now?

Proprietary Code-o-rama:the AlphaImageLoader Filter

Ie4+/win supports a variety of non-standard, largely ridiculous visual filters that your can apply to any image ' s style. Can, for instance, fade in ' an image with a gradient wipe, or make it stretch ' to ' full size, or ' even make I T swipe into place circularly, like a scene change in Star wars.

A non-pointless Gem Among these AlphaImageLoader are the filter, which is supported in Ie5.5+/win. When used to display a PNG, it allows for full alpha transparency support. All your have to be this:

<div id= "mydiv" 
	style= "position:relative; 
	height:250px; 
	width:250px;
Filter:progid:DXImageTransform.Microsoft.AlphaImageLoader»
(src= ' myimage.png ', sizingmethod= ' scale '); " ></DIV>

(line wraps are marked ».–Ed.)

And you ' re in business. Perfect Alpha transparency. This code works is great, with the small drawback that it's not part of the accepted Web Standard, and no other browser On the planet understands it.

Serving up PNGs with JavaScript

So the trick are to determine the user's browser and serve up the images appropriately:if, Ie5.5+/win we use AlphaImageLoader ; f a browser with native PNG support, then we display PNGs the normal way; If anything else, then we display alternate GIFs, because we can ' t be sure that a PNG would display correctly or at all.

Using a slightly tweaked version of Chris Nott ' s Browser detect Lite, we set some global variables to this effect that we can use later on.

If ie5.5+ on Win32, then display PNGs with AlphaImageLoader if (Browser.isie55 | | browser.isie6up) && browser. IsWin32) {var pngalpha = true;/else, if the browser can display PNGs Normally, then do, else if (BROWSER.ISGEC KO) |»| (browser.isie5up && Browser.ismac) | »| (Browser.isopera && browser.iswin »&& browser.versionmajor >= 6) |»| (Browser.isopera && Browser.isunix »&& browser.versionmajor >= 6) |»| (Browser.isopera && browser.ismac »&& browser.versionmajor >= 5) |»| (Browser.isomniweb && »browser.versionminor >= 3.1) | »| (Browser.isicab && »browser.versionminor >= 1.9) | »| (BROWSER.ISWEBTV) | »| (Browser.isdreamcast)) {var pngnormal = true;}           

(For the "faint of Heart:complete source code for all" The examples we cover is available in the end of the the article.)

Tactic 1:quick and Dirty with Document.writes

The simplest, most reliable way to spit out PNGs are using inline document.writes based on the above detection. So we use a function like this:

function Od_displayimage (Strid, strpath, Intwidth,»Intheight, strclass, Stralt) {if (Pngalpha) {document.write (' <div style= ') Height: ' +intheight+ ' px;»width: ' +intwidth+ ' px; »filter:progid:dximagetransform.microsoft.alphaimageloader» (src= \ ' +strpath+ '. png\ ', sizingmethod=\ ' scale\ ') "»id=" ' +strid+ ' "class=" ' +strclass+ ' ">< /div> '); else if (pngnormal) {document.write (' 
        »width=" " Span class= "Linewrap" >»height= "' +intheight+ '" name= "' +strid+ '" 
        »border= "0" class= "' + Strclass+ ' "alt=" ' +stralt+ ' "/>"); else {document.write (' »width=" ' +intwidth+ ' "»height=" ' +intheight+ ' "name=" ' +strid+ ' "»border=" 0 "class=" ' +strclass+ ' "alt=" ' + stralt+ ' "/> '); } } 
       

Now we can call the Od_displayimage function from anywhere on the page. Any javascript-capable browser'll display an image, and, if we want to is really careful, we can accompany each call wit H a <noscript> tag that contains a regular reference. So the respectable browsers get PNGs normally, Ie5.5+/win gets, them with the filter, and all other browsers get regular GI Fs, whether they have JavaScript turned on or not.

It ' s a time-tested method, but what if we want more control over our PNGs?

Tactic 2:the Beauty & majesty of Objects

When I told the "Programmer in the" office next door that I is writing this article, he took one look at my code, glowered At me, and said, "fool." Where ' s the abstraction? You are need to use objects. "

So now we are have a JavaScript object to display PNGs. Here's how we use it:

 

That ' s it. The cool thing about the "Opacityobject is" we just pass it a DIV ID and a image path and we ' re done. Using the appropriate technique, it applies the image as a background of the DIV, and from there we can do whatever we wan T with it. Fill it with text, move it across the screens, resize it dynamically, whatever–just like any other DIV.

The object works in any CSS 1-capable browser so can dynamically apply a background image to a DIV with JavaScript. It ' s completely flexible, and we could even use it in the ' above function.

The trade-off is that it doesn ' t degrade as nicely. Netscape 4.7/win/mac and Opera 5/mac, for instance, won ' t display a image at all. And it has another significant problem, which is this:

Ie5/mac only supports alpha transparency then the PNG resides in a tag, not when it ' s set as the background Propert Y of a DIV. So PNGs displayed with the opacityobject would appear 100% opaque in Ie5/mac. This problem is especially frustrating because Ie5/mac are the only browser which natively supports PNG and behaves this WA Y. We ' ve notified Microsoft about this apparent bugs and hope for the it to being fixed in a upcoming release.

But for now, this issues are the trade-off for flexibility. Obviously, choose the right tactic based on the particular needs of your project. Between them both, you can do pretty much anything with pngs–like, for instance ...

Example 1:translucent Image on a Photo

In this simple example, we are here to how the same 80% opaque PNG can is displayed on any kind of background:translucent the Image o n a Photo.

Example 2:anti-aliased Translucent Navigation with rollovers

What a beautiful thing it would be, I ' m sure you ' ve thought from time to time, to create translucent anti-aliased t Hat work on any background. So, check it out:anti-aliased translucent navigation with rollovers.

Mouse over the images, observe the behavior of the rollovers, and click ' Change background ' to ' how ' images behave o n different backgrounds. Then View the source. There are a few things worth noting here:

  • To preload the correct images, we create a variable called, which contains either strExt ". png" or ". gif." As long as our PNGs and alternate GIFs to the same names except for the file extension, the browser'll only preload the Images that it's actually going to use.
  • We Create a class called Pnglink and set the cursor property to "pointer." We pass this class name to the function as we call it, and the function applies the class to the PNG. The "result is" that "user" s pointer turns into a cursor as he rolls over the image links, even though, in Ie5.5+/win, They ' re really just divs. (for your might also want to add "Display:block" or "Display:inline" to your PNG class, depending on How do you ' re using the images, to make them display correctly in Netscape 6. (For details, Better living through XHTML.)
  • We also use a couple of the rollover functions specifically for displaying PNGs. It turns out this, while it's possible to dynamically swap out PNGs using AlphaImageLoader the, Ie5.5+/win has a tough time of it; ' s damn slow, too slow for effective rollovers. What works better are to apply a background color to the DIV that contains the png–the color would shine through the Trans Parent part of the image, and do it fast, too. When we call the function, we send along the name of "the" to be displayed and a HTML Color–ie5.5+/win'll display The color, and the others'll display the image.
  • Notice How those images even have drop shadows. Could stick any background image or color behind them and they would still look great, even if the PNGs were Y Transparent. Is this cool or what?

Example 3:floating Translucent DIV with HTML Text Inside

In the ' the ' two examples, we used the quick-and-dirty function from tactic one. Now, we want we are PNG to interact with the "the" and "so" we display it with the opacityobject.

But Remember–there are drawbacks to this approach (= above), the most heartbreaking of which of-this example does N ' t work perfectly on IE5/MAC. If that is causes you pain, then there ' always the quick and dirty function. Otherwise, read on.

We create a DIV, give it ID, and assign any style properties we want to it–height, width, font family, etc.

Then we pass along the ID of this DIV when we instantiate the Opacityobject. We pass along the "image path", too, and now we have a DIV with a translucent background. cool!

Next we put some HTML text in the DIV and apply another unrelated object method to it (this object has no The opacityobject–it could is any code for you have lying around). Now we can move the translucent DIV around the screen. wheee! Floating translucent DIV with HTML Text Inside.

So there's a glimpse of what ' s possible with the opacityobject. Hardcore css/dom folks, go nuts.

variably opaque-r-you

Download the source code for the object, functions, and examples we covered. All the code relies in our tweaked version of Browser detect Lite, which is included as. Variable Opacity Source Code.

One PNG and one PNG only

This is all very exciting, but, as with many achievements-get web developers excited, making PNG work in today ' s brow Sers simply shouldn ' t be this hard. You are might consider signing the petition to persuade Microsoft to provide full PNG support in Internet Explorer. With any luck, this article would soon be obsolete.

In the meantime, post no ideas for improvements to this code in the discussion forum for this article. The PNG home site, for instance, talks about a few other obscure browsers that should support alpha transparency, and but that Haven ' t been verified yet. If you can verify any of those claims, or have any other valuable input, let us know, and we ' ll update the code ACCORDINGL Y.

Resources

    • PNG Home Site
    • alphaimageloader Filter page on MSDN
    • PNG Behavior at WEBFX Alternate way to make PNGs display in IE. Involves using the Runtimestyle object. The downside with this, approach is, it only correctly displays a PNG if it ' s displayed within a tag, not if it ' s a CSS background image

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.