Hacker News new | past | comments | ask | show | jobs | submit login
SVG has more potential (madebymike.com.au)
428 points by kp25 on Sept 26, 2016 | hide | past | favorite | 101 comments



SVG is too complex/heavy for simple tasks and actually is not that good for complex tasks - more or less complex image requires special editing WYSIWYG application to create it.

Let's imagine that you need to render simple icon using CSS that should change color on :hover:

   div.icon { 
     background: url(simple.svg) no-repeat; 
     background-size: 1em 1em; 
   }

   div.icon:hover { ??? what to do here to change the color ??? }
Just to render this thing you will need: to download the file, parse SVG, build DOM tree and "play" that DOM tree on canvas. Each task is not trivial.

While ago I've proposed at w3c-styles simple and lightweight solution for vector images and shapes in CSS - so called path URLs:

   div.icon { 
     background: url(path:c 50,0 50,100 100,100 c 50,0 50,-100 100,-100) no-repeat; 
     background-size: 1em 1em; 
     stroke: #000; /* vector stroke color */
   }

   div.icon:hover { 
     stroke: #F00; 
   }

The path uses the same format as "d" attribute in SVG's <path> element:

   <path d="c 50,0 50,100 100,100 c 50,0 50,-100 100,-100" fill="#000" /> 
Parsing is trivial and rendering of such "images" is just a set of primitive drawing operations. No DOM or anything like that.

More on the subject (with illustrations in Sciter) : http://sciter.com/lightweight-inline-vector-images-in-sciter...


You can do that (hover effects via CSS), as long as you include the SVG in the HTML directly, not link to it as a file.

I believe this is what Github recently started doing:

https://github.com/blog/2112-delivering-octicons-with-svg

> You can see we’ve landed on directly injecting the SVGs directly in our page markup. This allows us the flexibility to change the color of the icons with CSS using the fill: declaration on the fly.


I would argue that rendering simple paths is not really the goal of CSS (or implementing icons for that matter). We already have images, we already have fonts. If there is a third way to render simple vector paths then transitioning to something more powerful (when somebody decides that they want colour in their icons) will be just more painful.


> I would argue that rendering simple paths is not really the goal of CSS

The goal of CSS is styling and decoration, simple vector paths seem comparable to border images (and border image slices) and a simple and great way to implement responsive decorative elements.


>> more or less complex image requires special editing WYSIWYG application to create it

I agree, it's like having to deal with images all over again; which we all know was a severe problem for the industry.

>> ??? what to do here to change the color ???

You see, that's because you picked one of the ways to use SVG that doesn't work the way you say you want it to. You are ignoring the other ways to handle the situation without the problem you're claiming. I would say you are being borderline dishonest just to make your false point.

As for the path idea, I don't think I would necessarily be against such a thing. But it would seem unwieldy with a complicated path.


What about:

  img.some_icon element:hover {color: brown};


Look no further than D3.js as an example of the kind of visualisations which are possible with SVG.

https://github.com/d3/d3/wiki/Gallery

At least this is what introduced me to working with SVG. As much as I like D3, mainly for charting, it's not the easiest thing to pick up.


Whoa that "mower demo" is really messing with my vim navigation muscle memory.


If you skip the whole .enter() pattern then D3 is more approachable, IMHO.


.enter() was sort of confusing for me at first, but you lose the data-binding goodness of D3 if you drop it. I think the real issue is that the tutorials don't really explain it correctly: .enter() is where you add things and make changes that will be with the nodes for their lifetime. Do that, and then do your update logic (setting path attributes & fills, etc.). Don't run update logic when instantiating nodes, except for animation.


You can think of .enter() as React working in 1 way and under your explicit control instead of automagically. It's a one-way binding between your data and your DOM, with the data being the source of truth.


d3v4 is improving the logic around .enter() a bit. See https://medium.com/@mbostock/what-makes-software-good-943557... Search for "Removing the magic of enter.append"


You can also use Vega or Vega-Lite and let d3 be the low-level architecture:

http://vega.github.io/

https://www.youtube.com/watch?v=Y8Fp9z-9DWc

https://vimeo.com/177767802

I especially like how they handle interaction (event streams/signals; about six, seven minutes into the youtube video).

Supposedly there's a big update coming late fall, that upgrades vega and vega-lite to the latest version of D3. It also (finally) introduces the interactive bits to vega-lite.


SVG is amazing, my main concern about it. it is because it creates a huge burden to browser developers. The spec is huge [1]. And some parts are outdated[2].

[1] https://github.com/WebKit/webkit/tree/master/Source/WebCore/... [2] https://developer.mozilla.org/en-US/docs/Web/SVG/SVG_animati...


> SVG is amazing, my main concern about it. it is because it creates a huge burden to browser developers.

Yes, it would have been better if SVG was designed on top of something simpler; and this something simpler could be implemented by browser developers. Probably, such an approach is more secure too. But, I guess it is too late now.


I imagine they could implement it on top of Canvas/WebGL.


Like https://github.com/canvg/canvg (which AFAIK doesn't do hit testing like 'real' SVG, but is a promising start).


Browser support is kind of okay. The problem is more that it is hardly supported outside of browsers because of the complexity


To be fair, this is equally true of HTML.


I am using svgs in a project now.

- The first issue was the designer Im working with didnt know how to export to svg.

- Second problem is my svgs ended up with very weird numbers and groups. Such as the main groups offset was -60, 190 then another group to dlightly compensate. Then the paths themselves compensated further.

- Another issue is "cutouts" are nonintuitive for designers and also complex to reverse when they are curves.

- Another issue is linking and styling to an external svg. Despite you can put them in an image tag, it cannot be styled this way. If you put it inside a use tag, styling externally requires targeting ids.

- anothwr issue is that they dont follow the normal rules of width/height. By default they are 300x150 and takes a bit of patience to ensure they exist as 100% width (which I assumed was default)

Other than that, I am quite pleased with the format and am expecting great things for it!


Hand-written SVG, treated as elements of the markup (rather than an external black-box object or image), usually works well. It's easily* styled, scripted, and has good clean structure and values. There are, however, a couple of problems.

Hand-writing a complex graphic is difficult! (ex: editing coastlines on a map) Unfortunately, current WYSIWYG editors produce bloated, illogical output full of bizarre measurement schemes, unnecessary translations, and incompatible proprietary garbage - sort of like the bad old days of Frontpage and Dreamweaver.

*There are also some quirks in both styling and scripting them (as others have mentioned, height is one, another is having to use NS versions of DOM functions instead of normal ones - but only sometimes).

Maybe by the time SVG turns 21, those things will be mostly sorted out. It's still in its awkward teenage years.


An alternative to to hand-written SVG is to use a (Go) library like svgo [1] to generate the markup programmatically. More info is also at [2] and [3]

[1] http://github.com/ajstarks/svgo [2] https://speakerdeck.com/ajstarks/the-other-side-of-go-progra... [3] https://www.youtube.com/watch?v=nuDO1oQxARs


Yeah, currently WYSIWYG tools generate pretty terrible SVG. Sketch is especially awful, Adobe almost as bad, Inkscape the least but still somewhat bad. SVGO helps sometimes with this, but it also sometimes chews up your document and spits out an empty SVG.


To my eye Inkscape was the worst, while Illustrator and Sketch were both OK'ish. Inkscape can create pretty complex transformations on groups that are not necessary. It can also easily screw up integer coordinates and somehow add fractions to them. It's a real shame. On one occasion I rewrote an SVG file generated by Inkscape and made it literally 20 times smaller. Something like from 200k to 10k. Never used the poor thing again.


Save as "optimized svg" helps a lot as a first step.


Discovering this has helped me a lot. SVGO is great, but sometimes it breaks my SVGs. Saving as Optimized SVG from Inkscape has never caused problems and the file sizes are very close.


Yes, it is a real shame, because Inkscape in itself is really awesome. For me the best vector drawing tool available ...

But I also gave up trying to use the output for scripting. It would have been a way straight to madness ...


I read a Tweet where he claimed Affinity Designer had cleaner SVG then Illustrator . . can anyone confirm this.


I don't have Illustrator, but here are two SVGs generated by Sketch and Affinity Designer:

Sketch: http://pastebin.com/A1QRW6fT

Affinity Designer: http://pastebin.com/KxTgGQkN

I'm in the middle of building my first production app using SVG, and I've had less trouble from Affinity than Sketch.


SVG also has more risk: stored XSS, which isn't something you'd expect from a file whose MIME type starts with "image/".

https://github.com/w3c/svgwg/issues/266


Ah, you beat me to it.

A practical demonstration of XSS in an SVG is the following:

  <?xml version="1.0" standalone="no"?>
  <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

  <svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
    <polygon id="triangle" points="0,0 0,50 50,0" fill="#009900" stroke="#004400"/>
    <script type="text/javascript">
      alert(document.cookie);
    </script>
  </svg>
I see this in the wild all the time, though these days it's becoming less harmful as more developers learn to host their images (and all user uploaded files, really) on a separate CDN.


Wait, what? Why is embedding a script into an image allowed? WTF? I do not expect my images to be turing complete.


Note that it's disabled if the image is loaded with an img tag, so allowing users to embed arbitrary URLs as images is safe. The issue is if you allow uploading of svg files to your own domain, someone can then have their own site redirect to the svg or load it in a frame, at which point it can run scripts from your origin.


> Why is embedding a script into an image allowed?

Because it lets you create vector games:

http://public.codenazi.fastmail.fm/asteroids_dynamic.svg

(a better use would be stuff like D3-style interactive charts)

Warning: I never finished that project because SVG rendering was too slow ~6 years ago. Frames would drop on every reflow after any DOM change. Arrows move, space shoots. Collision checks are on so the shield (x) works, but the death animation is disabled in that version.

I actually agree that images shouldn't be Turing complete. That's unnecessary in almost every normal situation and only adds attack surface. However, there is a place for animated vector graphics.


>I do not expect my images to be turing complete.

An image of type "image/svg+xml" is as powerful as a text of type "text/html". In both cases their mime-type could be considered a misnomer.

In general I find it more helpful to think of SVG as a xhtml-like format with tags for arbitrary shapes. It has full support for interaction, state, javascript, css and almost anything else you expect from a html document.


SVG is vector, not raster, and in one way of thinking, is embedding instructions on how to present and manipulate an image or set of graphics directives.

How close it is to Turing complete I'm not sure -- I've played with them a tad, enough to find them quite adaptable and useful, but have also seen stuff, much of it from David Daley (https://ello.co/ddailey) which boggles my poor little brain.


SVG lets you use ECMAScript, and ECMAScript is Turing-complete.


Thanks.


That's exactly the same as regular HTML


And more. I got a bug bounty by uploading a malicious svg witch would get parsed and fetch external resources, even read local images.

If your app receives and parses svg server side you might have a hole there.


> a malicious svg witch

You got me interested there ;)


Forgive my ignorance, but why would anyone ever need to parse an SVG server side?

Now that you got me thinking, SVG might be a decent, if somewhat large, format for accepting sketches from users. Something like "draw a map, and we'll find it on Google maps for you". But I am certain that that (SVG user input) isn't a thing yet.


Maybe you need PNG thumbnails for user-uploaded SVGs.


When I first heard about svg, I was excited. Finally everybody getting behind a vector graphics format... and since then the more I see the worse it looks. A boosted, text-oriented, JavaScript-enhanced resource monster. All the worst attributes of HTML, but in vector graphics.

Did anybody want this? I know I wanted a jpg of vector graphics - a resource-friendly small system for embedding vector graphics into things. Something where I don't have to worry about an image having an xss vulnerability. Something that degrades gracefully so it can still work in some form on an anemic piece of equipment.

But no. We throw bigger and heavier hardware at more trivial problems.


Did anybody want this?

Yes.

SVG is not a lightweight vector graphics format, which seems to be what you were hoping for. I agree that such a format would be useful as well.

However, for better or worse, web apps are a thing in 2016, and that means we need formats that lend themselves to programming and interaction. Having SVG do that for vector graphics is useful for much the same reasons as having HTML do that for text-based content and forms.


Agreed, a lightweight vector graphics format would certainly be welcome. However, the stuff SVG is capable of doing is not trivial but mostly just poorly understood.

I think the article below is a good read and I sometimes wonder if some of the (unconscious) negative perception around SVG is because of the slowness of its adoption:

http://blog.siliconpublishing.com/2015/12/the-fall-and-rise-...

Having said that, I personally find efforts to make SVG better understood (articles, books, tutorials etc) somewhat lacking, although that might just be a personal opinion.


Text-oriented... what did you expect? Binary formats are tough to standardize. We have raster images, video, audio files, and fonts, but very few of those formats are "web" formats. Most of them are designed around getting the most bang for your bit to the extreme--an MPEG-4 decoder is a real beast, to be sure, and it's hardly a good model for vector graphics. Vector graphics follow more of a human authorship pipeline (capturing a series of drawing commands) rather than machine capture pipeline (sampling data at a certain frequency). JSON, XML, JavaScript, HTML, even HTTP are built on text-oriented protocols and formats because text-oriented systems are easier to standardize and extend. MPEG-4, MP3, JPEG, Vorbis, are binary protocols because they only exist to represent and compress narrowly-defined multidimensional data.

Resource-friendly for small systems--how would we reduce memory consumption? The alternative model for vector graphics is what, PDF or PostScript? They're not exactly models of restraint. SVG looks positively austere compared to PDF or PostScript.

The closest thing I can think of to your ideal "minimal binary" vector graphics is something like TTF, which is basically its own little nightmare compared with SVG. TTF has its own vulnerabilities, its own proprietary scripting system compiled to bytecode, et cetera.

For me, SVG is doing a great job of enabling really cool things like D3, and at the same time hammering more nails into the coffin that is Flash--something far more a resource hog than SVG. And we don't really need more 90s-era formats, we've got plenty of those, thank you very much. SVG is to images what HTML is to documents. You can build simple, static ones easily enough, and you can also make a little bit of magic happen if you throw in some JavaScript.

It looks like in the future we'll be embracing more binary systems. TLS, HTTP/2, and WebAssembly are some examples. But it took a long time to get the institutional expertise to invent such systems, and if we had rushed to use binary instead of text in the early days, we would have probably gotten it wrong in a bad way.

Besides... the hardware is getting bigger and faster anyway... we might as well deliver some good experiences with it. Most of your battery is probably going to power the backlight and GPS radio anyway.


Flash--something far more a resource hog than SVG

If you had actually tried the first few versions of Macromedia Flash, on hardware of the time, you'd be surprised what could be accomplished. SVG is absolutely bloated in comparison.


I did, I taught classes on Macromedia Flash in the late 90s and early 2000s. That version of Flash simply isn't relevant to the modern web. You might as well be comparing RealPlayer with modern YouTube.

That said, I'm not sure what you would want to remove from "bloated" SVG.


It's like the W3C is reinventing Macromedia Flash, which was the choice for compact, interactive vector graphics around 10 years ago. I don't like what Adobe did to it after they bought Macromedia, but a subset of SWF would've fit the "resource-friendly small system for embedding vector graphics into things" use case very well. I wrote a substantial part of a SWF renderer --- in x86 Asm --- and it wasn't that difficult, because the format is actually quite simple to parse. An XML parser alone would've been larger than that, nevermind the SVG-specific processing on top of it.


On Windows, including historic, mobile and embedded versions, there are well-supported vector formats suitable for embedding images.

If your software paints stuff using GDI or GDI+, you can use windows metafile images, EMF/EMF+/EMZ.

If your software paints stuff using Silverlight or WPF or WinRT, the XAML format has descent support for vector graphics. On WinRT, it’s even compiled to binary form, BAML, to save resources in runtime.


Are vector graphics a trivial problem? I can't say that they are.


SVG is an untapped technology. It functions as an embedded document. When used within the Object tag, it can run javascript and CSS and ideally renders complex graphics with a much smaller payload. Also, they look amazing on all devices as they use the browser's rendering pipeline. SVG has been a fully supported standard for years.

https://sarasoueidan.com/blog/art-directing-svg-object/


You need paths built out of bezier segments and ways to fill them (Mono color and gradients). Maybe add some filters for effects like shadows, but that's it. Fairly trivial to implement.

Things like strokes and text that are hard to implement can just be converted into filled paths.


SVG as a representation language for draw programs is pretty good. Most draw programs don't utilize it fully. While SVG can represent dimensions as inches or mm, most programs only support dimensions as pixels, which makes SVG useless for CAD drawings.

If you need drawings with lines and boxes, Inkscape is very helpful. Most drawings in Wikipedia are in SVG, and many were drawn with Inkscape. You can update drawings in Wikipedia by bringing them into Inkscape and editing them, then checking them back in as an update. It's not a read-only notation, like Postscript.

Manually tweaking SVG text, though? Painful. It's encapsulated like XML, so you can, but you probably shouldn't. After you've done that, most draw programs won't be able to handle the fancy stuff. And really, drawing by typing text is like pounding a screw with a hammer.


> Manually tweaking SVG text, though?

Well, you could embed xhtml into svg and use regular html styling and text layout instead.


Only supported in Chrome and FF, no?


I think among the browsers it's only IE that doesn't support <foreignObject>, edge does.

But of course then there also is the issue of SVG editing tools that don't use a browser rendering engine


Timing! I just pulled a 4AM night last night creating my first ever Lua library, svglover[0], to facilitate SVG display in LÖVE[1], for a roguelike. Motivation was primitive[2] posted[3] last week. It's actually pretty easy to work with, even for lazy coders who find regex parsing acceptable like me[4] :) I'm no oldschool demo coder, but the coordinate transformation system is basically just a simple layer on top of an OpenGL pipeline. You don't even need viewbox, just groups with <g></g>

[0] https://github.com/globalcitizen/svglover [1] http://love2d.org/ [2] https://github.com/fogleman/primitive [3] https://news.ycombinator.com/item?id=12539109 [4] Make it work first, then make it work fast.


Gordon Lee[0] has made a ton of sophisticated SVGs for Wikipedia and its projects and recently presented at Wikimania. The Burj Khalifa[1] is one of my favorites. Inspired, I wrote this short script for fun that chops up a Blender file into PNGs[2] which I used to generate an animated SVG.

[0] https://en.wikipedia.org/wiki/User:Cmglee [1] https://upload.wikimedia.org/wikipedia/commons/0/06/Burj_Kha... [2] https://github.com/rndmem/ndice/blob/master/blend/d/render


SVG works for the trivial graphics use cases that are presented. But it falls apart for anything that requires more complexity, or dealing with documents of arbitrary complexity.

There is little provision for incremental rendering, and poor control and visibility of the internals of the rendering process. Once you dump your SVG to the browser, that's basically it. There's no way to find out what is going on.

It's really nice to just set a break point in your imperative Canvas code, or WebGL code and see exactly what is happening, and use all the standard debugging and profiling techniques. I have yet to see the same for SVG.


We solved this issue by using a rendering engine that has rich tooling, strong profiling and inspection capabilities, and is centered around predictability - React.

D3 v4 provides all of its goodness in loosely coupled modules with clear boundaries, so you can use it for all heavy lifting that it's amazing at (layouts, animations, shapes), then setState() all over the place to reflect the results in the DOM. Performance wise, the only limits we are hitting are native SVG limits on the number of nodes.

Our visualisations are complex (science and finance, to an expert and expertly distracted audience), but no more complex than the rest of the app. React paradigm is predictable, well known, and has a deep user base to lean on. Performance and inspection tools are solid. And the only difference is that the render method has a <g> instead of a <div>.


I’ve done similar things with React and SVG and I concur. As with scaling anything up using React, you need to be careful about how you structure your components so you can write shouldComponentUpdate everywhere you need it to get acceptable performance. That in turn means you have to be careful about how you represent the underlying data and any further data you derive from it to use when rendering your SVG. However, assuming those things have been done, I have found React+SVG to be a reasonably effective combination so far.


Why couldn't you achieve the same exact thing using a more traditional API, such as 2D/3D drawing?

I just don't see the huge value add. I've been doing visualizations for years and I think its way easier to just have a render loop that interacts directly with the graphics hardware via API based upon a current state that is being expressed for a given frame. You are free to structure your code however you wish and have none of the weird abstractions that come along with something like a declarative syntax like SVG. Not everything is well suited for a neat and orderly hierarchical abstraction and forcing yourself to adopt this abstraction for every project makes the code more complex.

I do think SVG is a good universal serialization format for most vector graphics, but if you're operating on data using SVG ends up (eventually) being more of a crutch than a help. If you don't believe me wait a year and look how complicated and convoluted your code will become.


Three years ago I was amazed by the versatility of SVG when I discovered it through D3 and it inspired our graphical designer to ask us designs never before seen in SaaS applications. Once you're willing to dive into the specifications, you'll find a treasure trove of possibilities.

There are some caveats beginning users should be aware of. First of all, better forget multi line text or sophisticated text layout within the SVG. I still think that's really missing in the current specification. As a commute project I once wrote the dynamic programming layout of Knuth (used in TeX) for SVG and JavaScript, but it was slow and didn't allow for multi line selections.

Another problem is rendering speed. SVG renderers can be fast, but you have to know what can be optimized by the gpu and what requires the CPU.


> First of all, better forget multi line text or sophisticated text layout within the SVG.

Can't you do it by embedding an HTML document into the SVG with foreignObject?

(edit: corrected name)


You are absolutely right [1]! It is not supported by IE, unfortunately.

[1] Made a small jsfiddle: https://jsfiddle.net/7y27wfuy/


I have had success with LaTex -> Inkscape -> SVG ... It was a kludge but got automatic fancy ligatures and such. YMMV!


Yes, but that wouldn't be dynamic (unless, of course, you run LaTeX and Inkscape in JavaScript, which would be cool but a bit wasteful).


Annoyances with SVG:

- Modularity is tough: you can nest <svg> or <g> elements with various transforms, but there's no first class layout concept.

- Pixel imperfections: browsers don't always render things 'nicely', and all sorts of horrid aliasing can happen.

- Styling options: all sorts of simple stuff like a double outline of a shape is really difficult (without extremely complex filters)

- Export: taking an SVG and exporting it as an image has lots of complications, especially with embedded fonts.

All that said, the output is mostly okay, and it's possibly the easiest graphical technology to integrate with React-style frameworks.


Pixel imperfections is a long-running problem with vector rendering engines. You can name "SVG" as a culprit, but any other format would suffer from the same problems because it is an implementation problem rather than a specification problem. The straightforward approach is "here's a buffer, let's think of the vector image as a series of drawing commands in that buffer", but that approach usually converts coverage to alpha at each step.

http://graphicdesign.stackexchange.com/questions/73601/is-th...

There are some interesting thoughts from nVidia on throwing GPU hardware at the problem. The specialized hardware on a GPU can handle coverage in a much more coherent way without paying a premium in processing and memory.

http://developer.download.nvidia.com/assets/gamedev/files/An...


if anyone has a link etc. where I can find more / better info on exporting an SVG as a image. It would be appreciated.


A poor man's version is to draw it onto a canvas and save the canvas, e.g.:

    var svg = '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" height="100" width="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>';
    i = new Image();
    var cnv = document.createElement('canvas');
    var ctx = cnv.getContext('2d');
    i.onload = function() {
        ctx.drawImage(i, 0, 0);
        console.log(cnv.toDataURL());
    }
    i.src = 'data:image/svg+xml;base64,'+ btoa(svg);


Now copy across all styles, embed all fonts and external images etc etc etc. Nightmare.



I'm wondering if it would be possible to parameterize SVG files. Suppose I have an icon in the file "icon.svg", it would be awesome if I could say in the CSS:

    .icon:hover
    {
        background-image: url("./icon.svg") main-color=#ff0000;
    }
where "main-color" is a parameter of the SVG file. So the icon turns red upon hovering (just an example).

Is something like this possible?


You'd probably inline the svg, and style it with CSS. i.e.

    .icon:hover .fill-main {
        fill: red;
    }
and

    <div class=icon>
        <svg height=16 width=16>
            <circle class=fill-main cx=8 cy=8 r=8/>
        </svg>
    </div>


background-image: url("./icon.svg?main-color=ff0000")

And serve icon.svg dynamically.

As others have mentioned, only for colors, there are easier ways.

But using this technique you can do anything.


Just be wary of code injection. It is XML, so it should be easy on any framework.


Yes, good idea.

Just wondering, is there a standard way of doing this? And do vector drawing programs support parameterization?


You can achieve something like that by setting the color of the containing element and then referring to currentColor within the styles for the SVG. If you use :hover and friends to change the color of the containing element, this does mean you can have the SVG change things like text or fill colours accordingly.

This technique is quite limited, though, as unfortunately it only allows passing of a single colour as a “parameter” to the SVG. In some cases, currentColor is redundant, as often if you just draw something in the SVG without specifying any colour explicitly, it will inherit the colour by default anyway.

Beyond that, you’re probably into scripting the SVG and all the vaguely-documented, non-portable, security-nightmarish possibilities that offers. For example, suppose you embed an SVG in your HTML like this:

    <!DOCTYPE html>
    <html>
    <head>
        <title>SVG Test</title>
    </head>
    <body>
        <object data="svgtest.svg" type="image/svg+xml" data-test-color="green" />
    </body>
    </html>
Then suppose the SVG file itself says something like this:

    <svg width="200" height="100" xmlns="http://www.w3.org/2000/svg" version="1.1">
        <rect x="0" y="0" width="200" height="100" rx="5" ry="5" fill="blue" />
        <script type="text/javascript"><![CDATA[
            console.log(window.frameElement.getAttribute("data-test-color"));
        ]]></script>
    </svg>
In theory, this should log "green" to your console, assuming you load both the HTML and SVG from compatible origins. This is because window.frameElement should refer to the <object> element and thus should allow access to its attributes, containing HTML document, and so on. (Note that this only works with embedding; using <img> to load the SVG should block the scripting.)

In practice, having just tried it in Chrome, Firefox and IE11, and loading from both a local disk and over HTTP, Firefox works in both cases, Chrome works over HTTP but blocks locally, and IE11 blocks in both cases (with window.frameElement being set to null in the blocked cases here). So sadly although this might be quite a useful technique if you can control your environment, it’s definitely not portable to all major browsers.


I really like SVG and this was a great article that contained many things I didn't know.

That said, I _tried_ to use SVG for something as simple as displaying some multiline monospaced text with whitespace preserved, and found it's either really hard, or actually not possible (unless you position each glyph manually). Is that really the case?


Why use SVG? Why not use CSS "white-space: pre-wrap"?


Well, I wanted SVG for its other features. Text is just a component of what I wanted to draw.


SVG has another interesting application: it can be used as a UI language for graphically rich and complex interfaces, almost game-like but not quite. You often see this kind of interfaces in audio, i.e. soft synths/effects. Though you will need to create your own extension to the markup and a subsystem that supports it in your OS, which in the end is not too complicated.

(Shameless self-plug as an example of an SVG-based GUI: https://itunes.apple.com/us/app/magnetola-vintage-cassette/i...)


I'd use it a bit more if I could style it with CSS without inlining the SVG source code within my HTML.


There are JS libraries that will inline SVG sprites for you


You can reference a style sheet from or include it directly in the image itself.


As a designer using SVGs across the web, there are a few drawbacks that are easy to fix:

- platforms like Twitter and Google Slides not accepting SVGs. I assume this is due to security concerns.

- Using SVGs on a website doesn't render with included WebFonts like normal text would. This leads to outlining text, which is a huge maintainability burden.

- Graphics programs have tones of SVG bugs. Even "leading" software like Illustrator and Sketch have a lot of bumps in the road.

Overall really excited about SVGs and use them as much as possible.


The main problems I've experienced:

* SVG's performance degrades sharply after a few hundred objects, then you have to use canvas or WebGL, or prerender to images * browser differences

otherwise good


We use SVG extensively at: https://fd.nl/krant


Generally I agree that SVG is awesome, but there are a variety of cross-platform issues with it and I worry it does not get enough serious use to see them addressed. The status quo is pretty good, but if you run into issues there is not always a work around.


I'm quite excited for SVG absolute positioning to become available in all browsers. It'll mean real responsive images, not just resizing, being able to move parts of the SVG instead of scaling proportionally, as the image is resized.


The issue that makes me not enjoy working with svg is the lack of negative scaling values. It makes it hard to do complex transformations on your vector widgets. Canvas is so much more better.


Style= "transform : scale(-1, 1)"

I remember this was very important fir a personal logi of mine


Hey! Thank you so much. I was working in Jupyter with Sympy to generate SVGs illustrating geometric relationships etc. (proofs of Pythagorean Theorem and stuff like that) and I had to subtract the y values from the height of the viewport to use the Sympy objects to generate coordinates for SVG.

This is so much cooler. :-)


I'm fairly sure you can set any affine transformation in SVG, just as in canvas. If need be by directly supplying the matrix.


This is why d3-node is the way to go... https://www.npmjs.com/package/d3-node


The second example is supported neither in Edge nor in Firefox, that's the problem. Extremely poor SVG support accross browsers.


Agreed. Just launched it over with different "modern" browsers and was disappointed by the support.


SVG? Wasn'it the new tech (10 Years after ARM) in 2000 that was supposed to be so wonderful it would be very easily adopted?

We are in 2016 ... ARM are still promising and SVG is still the new promising thing. Well, SVG has not taken a wrinkle, nor grown up a lot. It is still overpromising and complex.

Let me watch my backyard cristal balls for new innovations..

DCOM and RPC maybe? Oh, crumbs, it is called the cloud. All FW problems solved by using HTTP with cookies that are so safe.

I can't wait for the next new thing... GUI, Universal Display format (aka display postscript from NeXT), Xanadoo, XUL, sprites, linear framebuffers with blitters?




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

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

Search: