Do Not be afraid of SVG

WebExpo Logo Scared Ghost WebExpo Logo

Utilize It On Your Web Today

Marek Raida @xrevelon

Scalable Vector Graphics

  • SVG LogoW3C approved standard, since 1999
  • vectors = quality for every screen
  • focused on 2D graphics
  • HTML, CSS and JS friendly
  • XML based markup
  • DOM based with event model
  • well supported, even in MSIE 9+
  • accessible

How to create SVG

  • manually (just like you do HTML and CSS)
  • Palettevector editor like Illustrator or Inkscape
  • online editor like YouiDraw or SVG-Edit
  • utilize tons of documents from internet
    (tip: Google search = filetype:svg)
  • generate it via scripting

viewPort vs viewBox

SVG canvas is infinite. ViewPort is for internal percentage sizing & gives document's parent its dimensions.

  <svg width="200" height="200"><!-- content --></svg>

ViewBox = canvas visibility box/frame. Use it a lot, I do!

  <svg viewBox="-50 -50 200 200"><!-- content --></svg>

No one is mandatory, but they are very useful.

  <svg viewBox="-8 -8 80 80" width="88" height="88"><!-- content --></svg>

Integration ways

There are many ways how to integrate SVG in your web.
I recommend you to stick to some of these:

  1. Puzzleinline svg markup
  2. object tag
  3. img tag
  4. CSS background

Inline SVG markup

Mind necessity to keep XML syntax for all SVG markup

 …
 <h2>Some Title</h2>
  <div class="wrapper">
   
   <svg width="80" height="80" xmlns="http://www.w3.org/2000/svg">
     <circle cx="40" cy="40" r="35" fill="orange"/>
     <line x1="0" y1="0" x2="80" y2="50" stroke="green" stroke-width="4"/>
   </svg>
   <script>
     if (!document.implementation.hasFeature(
           "http://www.w3.org/TR/SVG11/feature#Shape", "1.1")) {
       // optional fallback here
     }
   </script>
  </div>
 <p>Some text…</p>
 …                      

Advantages

  • OKowner's document CSS applicable
  • manipulable via JavaScript
  • no extra file to load

Disadvantages

  • KOnot cacheable
  • cross-browser (MSIE) fluid size trick needed

Fluid design MSIE trick

Use if stretching is needed; fixed size works OK Live demo

    <style>
      .wrapper {
          width: 50%;
          height: 0;
          padding-top: 50%; /* (svg-height / svg-width) * wrapper-width */
          position: relative;
      }
      svg {
          position: absolute;
          top: 0;
          left: 0;
      }
    </style>
    <div class="wrapper">  
      <svg viewBox="0 0 50 50"></svg>
    </div>           

Object tag integration


  …
  <h2>Some Title</h2>

  <object type="image/svg+xml" data="turtle.svg" width="323" height="153">
      
  </object>

  <p>Some paragraph…</p>
    …
                        

Advantages

  • OKCSS from external stylesheet works
  • manipulable via JavaScript (externally & internally)
  • cacheable
  • intensive pre-compress possible (.svgz)

Disadvantages

  • KOowner document CSS not applicable
  • cross-browser (MSIE) fluid size trick needed

Fluid design MSIE trick

Setting width does the trick. Live demo

    <style>
      .wrapper {
          width: 50%;
      }
      .wrapper object {
          width: 100%;
      }
    </style>
    
    <div class="wrapper">  
      <object type="image/svg+xml" data="turtle.svg"></object>
    </div>           

Image tag integration

Good, old and familiar way to go…


    <img src="svg/dog.svg" alt="Dog" width="136" height="200"
        onerror="this.onerror=null; this.src='fallback.png'"/>
    <!-- with possible fallback using onerror attribute -->
                        
Dog

Advantages

  • OKcacheable and performant (pre-rendering)
  • safe and simple (sandboxed)
  • SMIL allowed (animated GIF substitute)
  • pre-compressing possible

Disadvantages

  • KOCSS from outside not applicable
  • no JavaScript manipulation
  • interactivity disabled (links, DOM events)

Fluid design MSIE trick

The same width trick like in object tag case. Live demo


    <style>
      img {
          width: 100%;
      }
    </style>
    
    <img width="323" height="153" src="svg/dog.svg" alt="Dog"/>
                        

CSS background image

    <style>
      .holder {
        width: 50%;
        height: 50%;
        background: url('img/turtle.png'); /* possible fallback trick */
        background-image: url(svg/fish.svg), none;
      }
    </style>
    
    <div class="holder"/>
 

Advantages

  • OKno tricks needed for modern browsers
  • cacheable, pre-compressible and performant
  • sandboxed with SMIL allowed

Disadvantages

  • KOthe same like in img tag case

Internal Media Queries

Embed your media queries inside SVG. Put it where it belongs! (OOP Encapsulation, proven practice)


House Icon

Is CSS drawing good enough?

Twitter logo created using HTML/CSS and crushed.

LegendTwitterLock
HTML+CSS
GZipped
2.9 kB
1.4 kB
impossible
to do ????
SVG
GZipped
1.2 kB
0.6 kB
24.7 kB
6.4 kB
PNG
crunched
4.1 kB
1.4 kB
124.7 kB
31.9 kB
Twitter Logo         Lock Image

Sharing CSS definitions

Inline code case, notice symbol element use.

<span style="color: darkgreen; fill: currentColor">My cute jellyfish
  <svg width="60" height="60">
    <symbol id="jellyfish" viewBox="0 0 400 500">
      <path d="M200,0.438c-90,0.772-172,72-192,160-6.89,28-8.74,57…"/>
    </symbol>
    <use xlink:href="#jellyfish"/>
  </svg>
</span>

<span style="color: #37abc8; fill: currentColor">Another cute jellyfish
  <svg><use xlink:href="#jellyfish" transform="rotate(180)"/></svg>
</span>              
My cute jellyfish Another cute jellyfish

External CSS & object

/* objectcase.css file, shared between HTML and SVG */ 
span, use#jellyfishExt { color: magenta; fill: magenta; }
<style> @import url(css/objectcase.css) </style>

<span>My shared jellyfish
  <object type="image/svg+xml" data="jellyfish.svg" width="60" height="60"/>
</span>              
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xhtml="http://www.w3.org/…">
  <style> @import url(css/objectcase.css) </style>
  
  <!-- I prefer this CSS linking instead of <?xml-stylesheet… ?> way -->
  <symbol id="jellyfish" viewBox="0 0 400 500">…</symbol>
  
  <use xlink:href="#jellyfish" id="jellyfishExt"/>
</svg>               
My shared jellyfish

JS manipulations

<input onchange="document.getElementById('tx').firstChild.data=this.value">

<svg>
 <path id="cr" d="M50,0c0,27.6-22.4,50-50,50s-50-22.4-50-50,22…"/>
 <text fill="green">
  <textPath xlink:href="#cr" id="tx">Text Writ Around The Circle</textPath>
 </text>
</svg>           
Text Writ Around The Circle

Line Drawing - script

MSIE compatible solution, DOM manipulation involved.

  <svg>
    <path id="drawMe" d="M 246,188 l3,12h2l5-6c0,4,1,6,5,7,3-5,8-2…"/>
    <script>
      var line = document.getElementById("drawMe");
      lineElem.style.strokeDasharray = line.getTotalLength();
      lineElem.style.strokeDashoffset = line.getTotalLength();

      // animation cycle follows
      window.requestAnimationFrame(…shift strokeDashoffset here…);
    </script>
  <svg>              
External link  

Line Drawing - SMIL

Synchronized Multimedia Integration Language solution.

  <svg>
    <path stroke-dasharray="1439" stroke-dashoffset="1439" d="M 246,188…">
      <animate attributeName="stroke-dashoffset" from="1439" to="0" 
        dur="4s" repeatCount="1" fill="freeze"/>
    </path>
  <svg>              
External link  

Line Drawing - CSS

Don't forget to add necessary prefixes (like -webkit-…)

 <svg>
   <style>
     .animate {
       animation: draw 4s linear 1 forwards;
     }
     @keyframes draw {
       100% {
         stroke-dashoffset: 0;
       }
     }
   </style>
   <path stroke-dasharray="1439" stroke-dashoffset="1439" d="M 246,188…"/>
 <svg>              
External link  

Use reflections

use tag creates live reflection of any existing node. It not only saves lines of code, but can do true miracles!!

Two Mirrors
  <g id="complexElementID" class="…">
    <circle …/> <text …/> <path …/>
  </g>

  <use xlink:href="#complexElementID" transform="scale(2)" class="some"/>

  <use xlink:href="#complexElementID" transform="rotate(90)" class="other"/>

Best SVG utilization


  1. maps of countries, regions even world
  2. Awardgraphs, diagrams and data visualizations
  3. technical plans and drawings
  4. interactive infographics
  5. colorful icons, superior to icon fonts
  6. and off course - responsive images ;-)

Limitations (= MSIE)

SVG doesn't work in MSIE8, but it's in decline already.
For SVG content doesn't work CSS: Transitions, KO Transformations nor Animations.
It is also the only browser not supporting SMIL Animations.
Scripting or other (non-CSS) ways could help mostly, yes, but it's a pity…

My recommendations

Follow these wise people and sophisticated tools:

Learn it and love it, SVG will not let you down

THE END

Thank you!

Thank you!

Presentation available at: svg.kvalitne.cz/webexpo/