recherche
Maisoninterface Webtutoriel CSSMa lutte pour utiliser et animer un gradient conique dans SVG

My Struggle to Use and Animate a Conic Gradient in SVG

The wonderful company I work for, Payoneer, has a new logo, and my job was to recreate it and animate it for a loader component in our app. I’ll explain exactly how I did it, share the problems I had, and walk you through the solution I came up with. And, as a bonus, we’ll look at animating it!

But first, I guess some of you are asking yourselves… Recreate it? Why?

The branding agency that designed our logo sent us a full set of assets categorized by themes. They came in all sizes and in every available format. We had everything, including SVGs, for the logo and the loader animation. But we couldn’t use them.

Here’s why. Let’s take a look at the logo:

The logo is a ring with a conic gradient that consists of five colors, and… that’s it. The problem is that SVG doesn’t support angled gradients (for now, at least), so when we export a design that has a conic gradient as an SVG, we need some sort of hack to get the desired result.

Now, I’m no expert when it comes to working with vector graphic software, so there might be a different (and perhaps better) way to do this, but I know that the most common way to export conic gradients to SVG is to convert the gradient element to an image and insert that image into the SVG as a base64 string. That’s also what we got from the branding agency, and I trust them to know the best way to export an SVG.

But, since the final SVG file now contains a PNG base64 string, the file size jumped to nearly 1MB, which might not be a total disaster, but it’s much higher than the 2KB that it should be. Multiply that difference by three themes (no text, light text, and dark text variations), and we’re looking at 3MB worth of images instead of 3KB worth of code. That’s a big difference, so we’ve decided to recreate the logo with SVG.

But how?!

Even though CSS fully supports conic gradients, SVG does not. So the first question I asked myself was how to create a conic gradient in SVG. Actually, I asked Google. And what I found was a lot of cool, unique, creative ways to add a conic gradients to SVG, most of them relying on some sort of clip-path implementation. I first created a short that represents the shape of the ring and used it as a clip-path on a simple element.

Next, I needed to fill the with conic gradients, but first, I had to find all the correct color stops to recreate the look. That took a while, but after a lot of fine tuning, I got a result I’m happy with:

div.gradient {
  background-image: conic-gradient(from 270deg, #ff4800 10%, #dfd902 35%, #20dc68, #0092f4, #da54d8 72% 75%, #ff4800 95%);
}

The last step was to replace the with something else that supports conic gradients, and the simplest way I’ve found is to use an SVG element with a regular

inside it, and a conic-gradient as a background-image. Then all I needed to do was to set the clip-path on the element, and that’s it.

So, that’s how I used a conic gradient in an SVG to keep the design fully vector and scalable with less than 20 lines of code, and less than 2KB in file size.

But that was the easy part. Now let’s talk animation.

The loader

Our app shows a loading animation every time a user logs in. We had been using a GIF file for it, but I had been meaning to update it to a pure CSS/SVG animation for months. The benefits are obvious: faster render means a more seamless loading experience, and a smaller file size means even faster loading. We simply get more for less, which is especially ideal for a loading animation.

Here’s the animation I was aiming for:

This type of animation is actually fairly easy with SVG. All we really need is a trick using stroke-dasharray and stroke-dashoffset. That was my starting point. I created a new in the center of the ring, removed the fill, added a stroke with the right stroke-width, and then worked on the animation.

It took me some playing around to get the movement just like the designers wanted it. I ended up using two animations, actually: one controls the stroke-dashoffset, and the second rotates the entire a full turn.

But, since the clip-path property refers to the fill of the shape, animating the stroke meant I had to solve one of two problems: I could either find a different way to animate the movement, or find a different way to add the colors to the stroke.

So I went back to Google and all of the creative ideas I found before, but most of them were pretty much un-animatable, so I started looking for a good non-clip-path way to add colors to the stroke. I looked at a few “out-of-the-box” solutions, checked out masking, and ended up with the simplest perfect solution:

.logoBlend {
  mix-blend-mode: lighten;
}

A lighten blend mode looks at the RGB colors of each pixel of the rendered element, compares it to the RGB value of the background pixel that’s behind it, and keeps whichever is highest. That means that the parts of the element that are white will remain white, and the dark parts will get the values of the background pixel.

By adding a white to the black path, I essentially blocked anything that’s behind it. Meanwhile, everything that’s behind the animated black stroke is visible. That meant I could bring back the with the conic-gradient, put it behind the mix-blend-mode layer, and give it a simple rotate animation to match the design.

Note that the end result of this method will have a white background, not transparent like the static logo, but I was fine with that. If you need to, you can flip it around, use black background, and hide the light parts of your element by setting the blend mode to darken.

Final touches

I was pretty much done at this point, and quite happy with the end result. But a couple of days later, I got a Lottie-based JSON file from the branding agency with the exact same animation. In retrospect, maybe I could spare my work and use their file, it would have worked just fine. Even the file size was surprisingly small, but it was still 8✕ bigger than the SVG, so we ended up using my animation anyway.

But, that meant I had one last thing to do. The Lottie animation had a “start animation” where the small orange dot grows into view, and I had to add it to my animation as well. I added a short 0.5s delay to all three animations as well as a scaling animation in the beginning.

Click on “Rerun” on the Pen to see the animation again from the initial dot.

That’s it! Now my company has a new logo and a set of lightweight, fully scalable assets to use across our web platforms.

And for those of you wondering, yes, I did end up creating a nice little Logo component in React since we’re using it. It even renders the SVG according to a theme passed to it as a prop, making the implementation easier, and keeping all future changes in a single location.

What about you?

Do you think there’s a better way to get the same result? Share your thoughts in the comments! And thank you for reading.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration
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
CSS Flexbox vs Grid: une revue complèteCSS Flexbox vs Grid: une revue complèteMay 12, 2025 am 12:01 AM

Le choix de Flexbox ou de la grille dépend des exigences de mise en page: 1) Flexbox convient aux dispositions unidimensionnelles, telles que la barre de navigation; 2) La grille convient aux dispositions bidimensionnelles, telles que les dispositions de magazines. Les deux peuvent être utilisés dans le projet pour améliorer l'effet de mise en page.

Comment inclure les fichiers CSS: méthodes et meilleures pratiquesComment inclure les fichiers CSS: méthodes et meilleures pratiquesMay 11, 2025 am 12:02 AM

La meilleure façon d'inclure des fichiers CSS est d'utiliser des balises pour introduire des fichiers CSS externes dans la pièce HTML. 1. Utilisez des balises pour introduire des fichiers CSS externes, tels que. 2. Pour les petits ajustements, le CSS en ligne peut être utilisé, mais doit être utilisé avec prudence. 3. Les grands projets peuvent utiliser des préprocesseurs CSS tels que SASS ou moins pour importer d'autres fichiers CSS via @Import. 4. Pour les performances, les fichiers CSS doivent être fusionnés et CDN doit être utilisé et compressé à l'aide d'outils tels que CSSNANO.

Flexbox vs Grid: Dois-je les apprendre tous les deux?Flexbox vs Grid: Dois-je les apprendre tous les deux?May 10, 2025 am 12:01 AM

Oui, vous émeuble-chouchoudion-dimensionnal, flexiblelayAndavigationMenus.2)

Mécanique orbitale (ou comment j'ai optimisé une animation de clés CSS)Mécanique orbitale (ou comment j'ai optimisé une animation de clés CSS)May 09, 2025 am 09:57 AM

À quoi cela ressemble-t-il de refactor votre propre code? John Rhea sépare une vieille animation CSS qu'il a écrite et traverse le processus de réflexion pour l'optimiser.

Animations CSS: est-il difficile de les créer?Animations CSS: est-il difficile de les créer?May 09, 2025 am 12:03 AM

CSSANIMATIONSARENOTINÉMENT HAUTS BUTREQUIREPRACTICIT ENCRIPTION DES PROFESSIONS DESPROPERTIES ET TROUVEMENT

@KeyFrames CSS: les astuces les plus utilisées@KeyFrames CSS: les astuces les plus utiliséesMay 08, 2025 am 12:13 AM

@ KeyframeSispopulardUetOtsSversatity andpowerCreatingsMoothcSSanimations.KeyTrickSinclude: 1) DefiingsMoothTransitionsBetwean

Compteurs CSS: un guide complet de la numérotation automatiqueCompteurs CSS: un guide complet de la numérotation automatiqueMay 07, 2025 pm 03:45 PM

CSSCOUNTERSAREUSEUSTTOMAGAUTAMAMATALUMENTSINDWEBDESIGNS.1) Ils ont été des cas de contenu, des listitems et de la forme.

Ombres de défilement moderne à l'aide d'animations axées sur le défilementOmbres de défilement moderne à l'aide d'animations axées sur le défilementMay 07, 2025 am 10:34 AM

L'utilisation d'ombres de défilement, en particulier pour les appareils mobiles, est un peu de UX subtil que Chris a couvert auparavant. Geoff a couvert une approche plus récente qui utilise la propriété d'animation-timeline. Voici encore une autre façon.

See all articles

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

Video Face Swap

Video Face Swap

Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Article chaud

<🎜>: Bubble Gum Simulator Infinity - Comment obtenir et utiliser les clés royales
3 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Système de fusion, expliqué
3 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers of the Witch Tree - Comment déverrouiller le grappin
3 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Version Mac de WebStorm

Version Mac de WebStorm

Outils de développement JavaScript utiles

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

mPDF

mPDF

mPDF est une bibliothèque PHP qui peut générer des fichiers PDF à partir de HTML encodé en UTF-8. L'auteur original, Ian Back, a écrit mPDF pour générer des fichiers PDF « à la volée » depuis son site Web et gérer différentes langues. Il est plus lent et produit des fichiers plus volumineux lors de l'utilisation de polices Unicode que les scripts originaux comme HTML2FPDF, mais prend en charge les styles CSS, etc. et présente de nombreuses améliorations. Prend en charge presque toutes les langues, y compris RTL (arabe et hébreu) ​​et CJK (chinois, japonais et coréen). Prend en charge les éléments imbriqués au niveau du bloc (tels que P, DIV),

SublimeText3 version Mac

SublimeText3 version Mac

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

PhpStorm version Mac

PhpStorm version Mac

Le dernier (2018.2.1) outil de développement intégré PHP professionnel