Hacker News new | past | comments | ask | show | jobs | submit login
Magical SVG Techniques (smashingmagazine.com)
370 points by thm on May 27, 2022 | hide | past | favorite | 44 comments



Great article and great collection of links!

I have taken up coding simple SVG icons by hand, and it's easier than it looks. Also, a great feature of SVG is the <defs> element, which lets one define shapes anywhere in an HTML page, and reuse them anywhere else (ie, not inside the same SVG).

So for example one can have an SVG element at the top of the page that lists a bunch of symbols in a global defs element, and reuse them at will some other places, without loading anything externally, or copy-pasting anything.

Used shapes can also be transformed: different colors for fill or stroke, scaled up or down, rotated, moved, etc.

> Good news, you can achieve fractional ratings with only CSS and inline SVG. Samuel Kraft explains how it works.

The technique presented in that other page is overly complex and convoluted.

Fractional stars can be done very simply in pure SVG with gradients. Here's an example of a grey star filled at 40% with red:

    <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 60 60">
      <defs>
        <polygon points="30,0 10,60 60,22 0,22 50,60" id="star"/>
        </defs>
      <linearGradient id="gradid">
        <stop offset="40%" stop-color="red"/>
        <stop stop-color="grey"/>
        </linearGradient>
      <use href="#star" fill="url('#gradid')"/>
      </svg>
In order to change the fill one just needs to manipulate the offset attribute of the first stop.

If there are many stars it can be tiresome to attach a different gradient to each star; what I do in that case is define 8 gradients from 10% to 90% fill, and reference them as needed for each object that needs to be filled to approx. that percentage.


It should be "viewBox" (with uppercase "B"):

https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/v...


Indeed, you're right. Can't edit the comment anymore though, sorry about that.


Do you use a tool for that? Or just the browser?


I've been using vscode with an SVG live preview extension.


Can you share which extension you use? There seem to be a few of them out there.


https://marketplace.visualstudio.com/items?itemName=jock.svg

It also does other IDE things like completions and MDN docs tooltips (quite handy for infrequent path authoring).

Don't remember why, but I also have a separate SVGO (sort of a formatter) extension.[1] Perhaps because of the brokenness in the other extension (noted on its marketplace page).

[1] https://marketplace.visualstudio.com/items?itemName=1000ch.s...


I just code in a text editor or in jsfiddle.net.

Changing gradients values or attaching a different gradient can only be done in JS (not CSS, AFAIK).


You can use a subset of css on svg too… and either css or js animation


You can also use the <animate /> SVG element to animate any SVG property with complex easing and timing curves.


One nitpick-- for inline SVGs your ids and refs will be in the global namespace. So this won't work well if you want to have multiple inline SVGs, as multiply-defined ids aren't allowed in the DOM.

Luckily XML has namespaces. Contact your local XML specialist for details on how to use them to solve this problem...

hides behind bush, snickers as confused XML specialist tells you that XML namespaces cannot solve this problem


It's true that ids are in the global namespace; but as long as each id is unique you can have as many inline SVGs as you want. In fact, that's one benefit of this approach: define shapes once, name them, and then reference them. If you do it like this it's much easier to avoid id conflicts.


I've been using defs to replace the font-awesome fonts and saving megabytes (to show the same icons).


Sounds interesting. Can you tell some more about it? Do I understand correctly that you are replacing icons with SVG's? Or even the font of regular text?


Not the OP, but you can save the paths as objects in your preferred programming language and then inject them into svg tags inline.


Instead of including FA's stylesheets and fonts, you just have an SVG with some defs.

Instead of having a <i class=...></i> to use an icon, which CSS turns into a specific character with a specific font name, which the font turns into a specific glyph from that font (usually SVG), you have a <svg><use ...></svg>

You can use the same icon because FA is already using SVG fonts, you can copy and paste the icons out.


Sarah Drasner's epic preso blew my mind 5 years ago, still relevant and eye-opening today:

https://slides.com/sdrasner/svg-can-do-that


Yo same here she's a genius. Opened me up to developing skills on the front end as being something that could actually be pretty fun.

It reminds me of flash from back in the day minus the horrible security holes and that's enough to put a smile on my face :)


These are great! I found out recently that GitHub supports SVGs in your profile README so couldn't resist setting up a huge animation on mine[1], you can't run JavaScript in SVGs unless they are inlined with the HTML but maybe it would be possible to setup a GitHub action to automatically generate it periodically.

https://github.com/jnordberg


Nice.

SVG is so versatile, the „hidden“ features like embedded html, iFrames, always funny to play with them. Sometimes in productive ways, sometimes for fun or for fun and profit like bugbounty hunting.


Kind of reminds me of... log4j.


I likewise couldn't resist doing something silly with an SVG animation on my profile [1], and I also have a micro startup [2] generating such SVGs periodically to serve as dashboards you can embed in your README.md. I'm interested in more of your predictions!

[1] https://github.com/arraypad/

[2] https://repography.com/


Haha love it!

The SVG posters are cool, if you're looking for some feedback try to find some way to reduce the lag on the site when previewing them. In Safari on a M1 the site slows to a crawl once the poster SVG is loaded, each click takes several seconds to register. Maybe you could do a low res server side rendered version? That could you let users preview their repos without them being able to just right-click the SVG as well


[1] at first I was like ... okay Head is going to the middle and „explode“ to spider view of commits and then I was like oh god yes he did it. The dvd thing.

Hahaha. Great work.


https://observablehq.com is a great place to create and play with SVG. Created by Mike Bostock who brought us d3 in js. It is a notebook environment and there are some promise-based conveniences among cells to be aware of. I find it fun to use and learn a lot from the community.


I started skimming for the term "animation" and my first deep dive ended with a Greensock wrapper:

> I use GreenSock for most of my animation because it makes sequencing animations a breeze and when working with SVG, I know I can rely on the transforms working consistently cross browser.

I mean, caniuse[1] shows SMIL support across all modern browsers. So if an SVG guru is using a wrapper lib I'm guessing it's yet another case of the web having an API that is "off-by-one" in the usability dept.

So what transform dragons lurk in SMIL (or any dragons for that matter)?

1: https://caniuse.com/svg-smil


My experience with SVG is that it renders great in all modern browsers, but Illustrator, Inkscape and other vector graphics editors don't support the latest SVG features.

I suspect that's why Shutterstock asks contributors to upload an EPS file, not SVG.


I can point to SVG functionality (2 or even earlier in some cases) missing from both browsers and Inkscape, but my feeling is that there’s more missing, and more important stuff missing, in browsers than in Inkscape. Where browsers are generally ahead is CSS in SVG.


It's actually not been that hard to hand-write an SVG that looks good in the major browsers, but then Inkscape renders it into a mess. The areas I tend to run into it are when fine-tuning text, and when using complicated clip-paths. Maybe I only have this impression because I hand-write svg watching my progress in a browser, and only check in inkscape after the fact. Perhaps if I started with inkscape I'd be noticing all the ways the browser fails on inkscape svg instead. Either way it's not an ideal situation.


EPS files definitely don't support the latest SVG features. They don't even support partial transparency (alpha)!


These are some very very awesome SVG works. A++ work by the original authors here and the dive into how they are done is very nice too.


Awesome inspiration material and great article! I would add also the following links maybe

https://css-tricks.com/guide-svg-animations-smil/

https://developer.mozilla.org/en-US/docs/Web/SVG/SVG_animati...

At Flovatar [1] we've been using SVG and SMIL animations as a way to achieve true composability and interactivity for our NFTs while also being able to store all the illustrations fully on-chain.

I just fell in love with SVG and highly encourage everyone to dig more into the potentials of it. You can even have fun and create epic pranks [2] with it :)

[1] https://flovatar.com

[2] https://twitter.com/flovatar/status/1520509399466483716


SVGs are how I first got in to learning JavaScript seriously.

However after months of slowly building my JS/SVG skills, I found out that no SVG renderer renders the shapes with mathematical accuracy.

And that was the first time I hit the learning curve known as “floating point precision”. I’ve since run in to so many of the other programming learning curves (like timezones! And how did everyone agree to taint the integrity of the unix epoch?), but I digress.

While the field of programming can be frustrating in it’s imprecision it’s also 100% worth learning, and SVG+CSS+JS is a wildly powerful mix that flies under the radar far too often.


Some SVG animation examples for learning:

https://ericfortis.github.io/web-animations/


There is really not much about SVG here. These are drawing techniques and little is specific to SVG. I was expecting something along the lines of using `stroke-dashoffset` to create loading bars. Almost everything here is just “think of something and paint it onto a canvas,” where the canvas’ technology is SVG.


I also find the SVG Primer (https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html) a useful reference with clear examples.


Some questions:

How can I set a CSS variable as the color of a path.

Is there a way to use SVGs as custom characters? Even better to allow copy-pasting them?


Here's an example (Sun) https://github.com/ericfortis/web-animations

Source Code: https://github.com/ericfortis/web-animations/blob/main/sun.s...

---

Yes, you can create a font out of svg files. For example, I've seen fonts with only the letters of the logo, so the logo can be written as text and displayed as designed.

BTW, I haven't done a font like that, but here are some instructions:

https://www.thoughtco.com/create-your-own-fonts-using-inksca...


Generative art in SVG is amazing. It's sort of like DALL E2 for people who are not lazy.


> Let’s look at some magical SVG techniques that you can use right away

So we're assuming a company/vendor/brand/person/whatever wants their site only working in the latest modern browser here are we?

Because there's always the caveat of backward compatibility that you have to consider. There are people stuck on older browsers (for whatever reason). SVG should be used sparingly and strictly for decoration. Don't build all your site's graphics with it. Use plain images for communicating ideas instead of SVG.


SVGs work on IE9 and higher plus every single version of Chrome and Firefox and Edge and Opera and Safari and Opera Mini. What more could you want? https://caniuse.com/svg


And at 99.81% full support on mobile browsers.

I can’t think of a particularly plausible case where someone is using a browser so old it can’t support SVG—because if they are, they are on something like IE 8, and they are obviously going to be running into way, way bigger issues.


no. you don't need to support older browsers. supporting older browsers only encourages people to not update their browsers. if they can't update their browser because some IT dept. said they can't then maybe if the whole internet is broken for them, the IT dept will finally let them update.


Most people with a browser limitation are using a very old personal computer or device which cannot run the latest browser or OS, or does not have sufficient resources to do so adequately.

And yes, much of the modern internet is broken for them, but the basic and essential services are not, and that's what they can afford to use.

They'll get an updated device eventually, when they save enough cash and the annoyances justify the spend for a replacement (perhaps second-hand), or when a friend upgrades and gives away their old kit for free. Either way, the replacements are often years old when obtained, so the wheel turns again.

There are a lot of people running old devices. You can see this in the OS version web request stats looking at old OS versions people would not run if they had recent devices. More subtly you can see it in the screen resolution stats.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: