Table des matières
PNG? What?
Binary Transparency: the Scourge of GIF
So What About Browser Support?
Now, what's missing from that list?
Proprietary Code-o-Rama: the AlphaImageLoader Filter
Serving up PNGs with JavaScript
Tactic 1: Quick and Dirty with document.writes
Tactic 2: the Beauty & Majesty of Objects
Example 1: Translucent Image on a Photo
Example 2: Anti-Aliased Translucent Navigation with Rollovers
Exemple 3 : DIV translucide flottant avec du texte HTML à l'intérieur
Variablement Opaque-R-You
Un PNG et un PNG seulement
Ressources
Maison interface Web tutoriel CSS Opacité variable multi-navigateurs avec échange PNG_Experience

Opacité variable multi-navigateurs avec échange PNG_Experience

May 16, 2016 pm 12:09 PM
png variable with

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 be using it on our sites instead of GIF. People have been saying this for years, and by now most of us have stopped listening. 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 1995, having cropped up during the now long-forgotten GIF scare, when Compuserve and Unisys announced they would begin charging royalties for the use of 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 the free, superior format and shun GIF forever. But over time, browsers continually failed to support PNG, and eventually most people started to forget 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 is a big deal, we must first understand one of the most annoying limitations of GIF.

Binary Transparency: the Scourge of GIF

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

For one, a GIF image can either use no transparent colors at all or have one color that's completely transparent – there are 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 color, or else the anti-aliased area around the transparent color will be surrounded by ugly haloing and fringing. If you've spent more than five minutes as a web designer, you know what I'm talking about.

The result is that any anti-aliased transparent GIF is inextricably tied to the background color of the web page on which it lives. If you ever decide to change that color, you must also change the GIF.

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

So What About Browser Support?

By now, of course, we'd all be up to our ears in PNGs if browsers supported them reliably. 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 not as bad as it sounds.

It turns out that most of the latest versions of the major browsers fully support alpha transparency with PNG – namely, Netscape 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, will, in fact, display a PNG, but it doesn't natively support alpha transparency. In IE5.5+/Win, the transparent area of your PNG will display at 100% opacity – that is, it won't be transparent at all.

Bugger. So what do we do now?

Proprietary Code-o-Rama: the AlphaImageLoader Filter

IE4+/Win supports a variety of non-standard, largely ridiculous visual filters that you can apply to any image's style. You can, for instance, fade in an image with a gradient wipe, or make it stretch from nothing to full size, or even make it swipe into place circularly, like a scene change in Star Wars.

A non-pointless gem among these is the AlphaImageLoader filter, which is supported in IE5.5+/Win. When used to display a PNG, it allows for full alpha transparency support. All you have to do is this:

<DIV ID="myDiv" 
	STYLE="position:relative; 
	height:250px; 
	width:250px;
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader<SPAN class=linewrap>&raquo;</SPAN>
(src='myimage.png',sizingMethod='scale');"></DIV>
Copier après la connexion

(Line wraps are marked ». –Ed.)

And you're in business. Perfect alpha transparency. This code works great, with only the small drawback that it's not part of any accepted web standard, and no other browser on the planet understands it.

Serving up PNGs with JavaScript

So the trick is to determine the user's browser and serve up the images appropriately: if IE5.5+/Win, then we use AlphaImageLoader; if 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 will 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 that
} else if ((browser.isGecko) |<span class="linewrap">»</span>
| (browser.isIE5up && browser.isMac) |<span class="linewrap">»</span>
| (browser.isOpera && browser.isWin <span class="linewrap">»</span>
	&& browser.versionMajor >= 6) |<span class="linewrap">»</span>
| (browser.isOpera && browser.isUnix <span class="linewrap">»</span>
&& browser.versionMajor >= 6) |<span class="linewrap">»</span>
| (browser.isOpera && browser.isMac <span class="linewrap">»</span>
	&& browser.versionMajor >= 5) |<span class="linewrap">»</span>
| (browser.isOmniweb && <span class="linewrap">»</span>
	browser.versionMinor >= 3.1) |<span class="linewrap">»</span>
| (browser.isIcab && <span class="linewrap">»</span>
	browser.versionMinor >= 1.9) |<span class="linewrap">»</span>
| (browser.isWebtv) |<span class="linewrap">»</span>
| (browser.isDreamcast)) {
	var pngNormal = true;
}
Copier après la connexion

(Note for the faint of heart: complete source code for all the examples we cover is available at the end of the article.)

Tactic 1: Quick and Dirty with document.writes

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

function od_displayImage(strId, strPath, intWidth, <span class="linewrap">»</span>
	intHeight, strClass, strAlt) {	
 if (pngAlpha) {
 document.write('<div style="height:'+intHeight+'px;<SPAN class=linewrap>&raquo;</SPAN>
		width:'+intWidth+'px;<SPAN class=linewrap>&raquo;</SPAN>
 filter:progid:DXImageTransform.Microsoft.AlphaImageLoader<SPAN class=linewrap>&raquo;</SPAN>
 (src=\''+strPath+'.png\', sizingMethod=\'scale\')" <SPAN class=linewrap>&raquo;</SPAN>
	id="'+strId+'" class="'+strClass+'"></div>');
	} else if (pngNormal) {
 document.write('<img src="'+strPath+'.png" <SPAN class=linewrap>&raquo;</SPAN>
	width="'+intWidth+'"<SPAN class=linewrap>&raquo;</SPAN>
 height="'+intHeight+'" name="'+strId+'" <SPAN class=linewrap>&raquo;</SPAN>
	border="0" class="'+strClass+'" alt="'+strAlt+'" />');
	} else {
 document.write('<img src="'+strPath+'.gif" <SPAN class=linewrap>&raquo;</SPAN>
	width="'+intWidth+'"<SPAN class=linewrap>&raquo;</SPAN>
 height="'+intHeight+'" name="'+strId+'" <SPAN class=linewrap>&raquo;</SPAN>
	border="0" class="'+strClass+'" alt="'+strAlt+'" />');
	}
}
Copier après la connexion

Now we can call the od_displayImage function from anywhere on the page. Any JavaScript-capable browser will display an image, and, if we want to be really careful, we can accompany each call with a

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 was writing this article, he took one look at my code, glowered at me, and said, “Fool. Where's the abstraction? You need to use objects.”

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

<html><head>
<script language="javascript" 
 src="browserdetect_lite.js" 
 type="text/javascript">
</script>
<script language="javascript" 
src="opacity.js" 
type="text/javascript"></script>
<script type="text/javascript">
var objMyImg = null;
function init() {
	objMyImg = new OpacityObject('myimg','/images/myimage');
	objMyImg.setBackground();
}
</script>

<style type="text/css">

#myimg { 
 background: url('back.png') 
 repeat; position:absolute; 
 left: 10px; top: 10px; 
 width: 200px; 
 height: 200px;
 }

</style>

</head>


<body onload="init()" background="back.jpg">

<div id="myimg"></div>
</body>
</html>
Copier après la connexion

That's it. The cool thing about the OpacityObject is that we just pass it a DIV ID and an 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 want with it. Fill it with text, move it across the screen, resize it dynamically, whatever – just like any other DIV.

The object works in any CSS 1-capable browser that can dynamically apply a background image to a DIV with JavaScript. It's completely flexible, and we could even use it in place of 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 an image at all. And it has another significant problem, which is this:

IE5/Mac only supports alpha transparency when the PNG resides in an <img> tag, not when it's set as the background property of a DIV. So PNGs displayed with the OpacityObject will appear 100% opaque in IE5/Mac. This problem is especially frustrating because IE5/Mac is the only browser which natively supports PNG and behaves this way. We've notified Microsoft about this apparent bug and hope for it to be fixed in an upcoming release.

But for now, these 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 see how the same 80% opaque PNG can be displayed on any kind of background: Translucent Image on 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 images that work on any background. Well, check it out: Anti-Aliased Translucent Navigation with Rollovers.

Mouse over the images, observe the behavior of the rollovers, and click “change background” to see how the images behave on different backgrounds. Then view the source. There are a few things worth noting here:

  • Pour précharger les images correctes, nous créons une variable appelée strExt, qui contient soit « .png » soit « .gif ». Tant que nos PNG et GIF alternatifs utilisent les mêmes noms à l'exception de l'extension de fichier, le navigateur ne préchargera que les images qu'il va réellement utiliser.
  • Nous créons une classe appelée pngLink et définissons la propriété du curseur sur « pointeur ». Nous transmettons ce nom de classe à la fonction lorsque nous l'appelons, et la fonction applique la classe au PNG. Le résultat est que le pointeur de l'utilisateur se transforme en curseur lorsqu'il survole les liens d'images, même si, dans IE5.5+/Win, ce ne sont en réalité que des DIV. (Vous souhaiterez peut-être également ajouter "display:block" ou "display:inline" à votre classe PNG, selon la façon dont vous utilisez les images, pour qu'elles s'affichent correctement dans Netscape 6. (Pour plus de détails, voir Mieux vivre grâce au XHTML .)
  • Nous utilisons également quelques fonctions de survol spécifiquement pour l'affichage des PNG. Il s'avère que, bien qu'il soit possible d'échanger dynamiquement des fichiers PNG à l'aide de AlphaImageLoader, IE5.5+/Win a du mal à le faire ; c'est sacrément lent, trop lent pour des retournements efficaces. Ce qui fonctionne mieux est d'appliquer une couleur d'arrière-plan au DIV qui contient le PNG – la couleur brillera à travers la partie transparente de l'image, et ce, rapidement également. Lorsque nous appelons la fonction, nous envoyons le nom de l'image à afficher et une couleur HTML – IE5.5+/Win affichera la couleur, et les autres afficheront l'image.
  • Remarquez comment ces images ont même des ombres portées. Vous pouvez coller n’importe quelle image ou couleur d’arrière-plan derrière eux et ils auront toujours fière allure, même si les PNG étaient complètement transparents. C'est cool ou quoi ?

Exemple 3 : DIV translucide flottant avec du texte HTML à l'intérieur

Dans les deux premiers exemples, nous avons utilisé la fonction quick-and-dirty de Tactic One. Maintenant, nous voulons que notre PNG interagisse avec d'autres codes sur la page, donc cette fois nous l'affichons avec OpacityObject.

Mais rappelez-vous : cette approche présente des inconvénients (voir ci-dessus), le plus déchirant étant que cet exemple ne fonctionne pas parfaitement sur IE5/Mac. Si cela vous fait mal, il y a toujours la fonction rapide et sale. Sinon, lisez la suite.

Nous créons d'abord un DIV, lui donnons un identifiant et lui attribuons toutes les propriétés de style que nous souhaitons : hauteur, largeur, famille de polices, etc.

Ensuite, nous transmettons l'ID de ce DIV lorsque nous instancions l'OpacityObject. Nous suivons également le chemin de l'image et nous avons maintenant un DIV avec un fond translucide. Cool !

Ensuite, nous mettons du texte HTML dans le DIV et lui appliquons une autre méthode d'objet sans rapport (cet objet n'a rien à voir avec OpacityObject – il peut s'agir de n'importe quel code que vous avez). Nous pouvons maintenant déplacer le DIV translucide sur l'écran. Ouf ! DIV translucide flottant avec texte HTML à l'intérieur.

Voici donc un aperçu de ce qui est possible avec OpacityObject. Vous les hardcore CSS/DOM, devenez fous.

Variablement Opaque-R-You

Téléchargez le code source de l'objet, des fonctions et des exemples que nous avons abordés. Tout le code repose sur notre version améliorée de Browser Detect Lite, qui est également incluse. Code source à opacité variable.

Un PNG et un PNG seulement

Tout cela est très excitant, mais, comme pour de nombreuses réalisations qui enthousiasment les développeurs Web, faire fonctionner PNG dans les navigateurs d'aujourd'hui ne devrait tout simplement pas être si difficile. Vous pourriez envisager de signer la pétition pour persuader Microsoft de fournir une prise en charge complète du format PNG dans Internet Explorer. Avec un peu de chance, cet article sera bientôt obsolète.

En attendant, postez vos idées d'amélioration de ce code dans le forum de discussion de cet article. Le site d'accueil PNG, par exemple, parle de quelques autres navigateurs obscurs qui devraient prendre en charge la transparence alpha, mais qui n'ont pas encore été vérifiés. Si vous pouvez vérifier l'une de ces affirmations ou si vous avez toute autre contribution précieuse, faites-le-nous savoir et nous mettrons à jour le code en conséquence.

Ressources

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
1 Il y a quelques mois By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
1 Il y a quelques mois By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
1 Il y a quelques mois By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Commandes de chat et comment les utiliser
1 Il y a quelques mois By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Comment convertir PNG en JPG sous Windows 11 Comment convertir PNG en JPG sous Windows 11 May 12, 2023 pm 03:55 PM

Comment convertir PNG en JPG sous Windows 11 Sous Windows 10 et 11, vous pouvez utiliser l'application Paint intégrée de Microsoft pour convertir rapidement des fichiers image. Pour convertir une image PNG en JPG sous Windows 11, procédez comme suit : Ouvrez l'Explorateur de fichiers et accédez à l'image PNG que vous souhaitez convertir. Cliquez avec le bouton droit sur l'image et sélectionnez Ouvrir avec > Dessiner dans le menu. Votre photo ou image s'ouvre dans l'application Paint. Notez la taille du fichier en bas de l'écran. Pour convertir un fichier PNG en JPG, cliquez sur Fichier et sélectionnez Enregistrer sous > Image JPEG dans le menu. Lorsque la ressource de fichier

Comment renommer l'extension de tous les fichiers d'un dossier, y compris les sous-dossiers Comment renommer l'extension de tous les fichiers d'un dossier, y compris les sous-dossiers Apr 14, 2023 pm 12:22 PM

Supposons que vous deviez renommer l'extension d'un fichier d'une extension à une autre, par exemple jpg en png. C'est facile, bien sûr ! Mais que se passe-t-il si vous avez plusieurs fichiers dont les extensions doivent être modifiées ? Ou pire, que se passe-t-il si ces multiples fichiers se trouvent également dans plusieurs dossiers et sous-dossiers, au sein d’un seul dossier ? Eh bien, pour une personne normale, cela peut être un cauchemar. Mais pour un geek, absolument pas. La question est maintenant : êtes-vous un geek ? Eh bien, avec l’aide de Geek Page, c’est définitivement le cas ! Dans cet article, nous expliquons comment renommer facilement l'extension de tous les fichiers d'un dossier, y compris les sous-dossiers de votre choix, d'une extension à une autre via une méthode de script batch. Avis:

Démystifier le mot-clé with en Python Démystifier le mot-clé with en Python Apr 14, 2023 am 11:31 AM

Beaucoup d'entre nous ont vu cet extrait encore et encore dans le code Python : with open('Hi.text', 'w') as f: f.write("Bonjour, là") Cependant, certains d'entre nous Certaines personnes ne le font pas savoir à quoi sert with et pourquoi nous devons l'utiliser ici. Dans cette lecture, vous découvrirez presque tous les problèmes pouvant être résolus. Commençons ! Tout d’abord, considérons ce que nous devons faire sans utiliser le mot-clé with. Dans ce cas, nous devons d’abord ouvrir le fichier et essayer d’écrire. Peu importe le succès ou l'échec, nous ferions mieux d'être

Avis PHP : Variable non définie : solution dans la solution Avis PHP : Variable non définie : solution dans la solution Jun 22, 2023 pm 10:01 PM

Pour les développeurs PHP, rencontrer des messages d'avertissement "Undefinedvariable" est une chose très courante. Cette situation se produit généralement lorsque vous essayez d'utiliser des variables non définies, ce qui entraînera l'échec de l'exécution normale du script PHP. Cet article explique comment résoudre le problème de « PHPNotice : Undéfinivariable : en solution ». Cause du problème : Dans un script PHP, si une variable n'est pas initialisée ou affectée d'une valeur, "Un

Quel est le format png ? Quel est le format png ? Dec 10, 2020 pm 04:16 PM

png est un format bitmap qui utilise un algorithme de compression sans perte. Le format PNG a trois formes : 8 bits, 24 bits et 32 ​​bits. Le PNG 8 bits prend en charge deux formes transparentes différentes. Le PNG 24 bits ne prend pas en charge la transparence. Le PNG 32 bits ajoute un 8 bits. canal transparent de bits au 24 bits, par conséquent, peut afficher 256 niveaux de transparence.

Quel est le format des fichiers png ? Quel est le format des fichiers png ? Feb 19, 2024 pm 08:32 PM

PNG est un format de fichier image courant, dont le nom complet est « Portable Network Graphics ». Il s'agit d'un format de compression sans perte conçu pour remplacer les formats JPEG et GIF couramment utilisés dans le passé. Le format PNG a été créé en 1995 par le graphiste Thomas Boutell et a gagné en popularité au fil des années suivantes. Le format PNG se caractérise par la prise en charge d'une compression d'image de haute qualité tout en conservant les détails de l'image et les informations de couleur. Comparable au format JPEG

Comment transformer des images en png Comment transformer des images en png Jan 19, 2021 am 09:14 AM

Comment transformer une image en png : 1. Ouvrez le logiciel PS ; 2. Recherchez l'image qui doit être traitée et importez-la dans le logiciel ; 3. Ajustez la couleur d'arrière-plan de l'image en blanc 4. Sélectionnez le " ; "Magic Eraser" et cliquez sur La zone d'arrière-plan de l'image qui doit être rendue transparente ; 5. Cliquez sur "Fichier" - "Enregistrer sous" dans la barre de menu, sélectionnez "png" dans le format de sauvegarde dans la fenêtre contextuelle, et exportez l'image au format png.

Quel est le format du fichier png ? Quel est le format du fichier png ? Feb 21, 2024 pm 09:30 PM

PNG est un format de fichier image courant. Il s’agit d’un format de compression sans perte, ce qui signifie qu’il ne perd pas la qualité de l’image. PNG signifie Portable Network Graphics. Le format de fichier PNG a été créé à l'origine par un groupe de développeurs en 1996 et était destiné à remplacer certains formats de fichiers limités et inefficaces tels que GIF. Le format de fichier PNG est basé sur un algorithme de compression sans perte et utilise des index, des palettes et des images en niveaux de gris pour stocker les données d'image. Comparé à d'autres formats d'image, PN

See all articles