© Alex Libby  2018
Alex LibbyBeginning SVGhttps://doi.org/10.1007/978-1-4842-3760-1_9

9. Incorporating SVG Libraries

Alex Libby1 
(1)
Rugby, Warwickshire, UK
 

Throughout the course of this book, we’ve explored many of the techniques we can use to create and manipulate SVG content – much of this will have been through manual effort using a text editor.

In some cases though, there may be instances where the effort required would outweigh the benefits gained; to avoid that, we may need to resort to using third-party libraries to help facilitate development. Fortunately, there are some good libraries we can use – in this chapter, we’ll explore some of the plug-ins available, and discover how we can make use of them within our own projects.

Why Use a Library?

This is indeed a good question – with the emphasis on speed and increasing usage of non-desktop environments (such as tablets or games consoles), we clearly need to be careful about which dependencies we introduce!

There is a very good reason why many of these libraries exist – although they each have their own take, or serve their own purpose, many exist to help abstract the grunt work required to modify SVG documents. This is a tedious process when using vanilla JavaScript, such as in this example:
var paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
  var paragraph = paragraphs.item(i);
  paragraph.style.setProperty("color", "white", null);
}
Take a library such as D3, for example – it does away with much of the code required for that last example, and simplifies it to this:
d3.selectAll("p").style("color", "white");

This code selects every instance of a p (or new paragraph) element, and styles the text white. D3’s ability to write this as a one-liner compared to the five lines used in the pure JavaScript solution is clearly a better, more efficient solution! The challenge though for us is to ensure we pick the right library; as is the case with many, each offers different facilities, or which may conflict with other libraries already in use within your project. To help narrow the choices, there are a few questions we can ask ourselves – we may not arrive at a final solution, but we can at least reduce the choices!

Choosing the Right Library

Choices, choices! Where does one start, I hear you ask…?

It is true that thanks to the power and flexibility of SVG, we are not short on libraries that can work with the format! We have options such as Snap.svg (which we cover elsewhere in this book); a library such as Paper.js ( http://paperjs.org/ ), designed to manipulate SVG elements on HTML5 Canvas; or Two.js ( https://two.js.org/ ), for drawing 2D shapes using SVG. It goes without saying that not every library will be a perfect fit; some may fit better than others, and that we may even have to use multiple offerings to satisfy our needs. That said, we can ask ourselves a number of questions to help reduce the variety of choice to a short list of contenders, before making the final decision.

The questions we ask should be common sense – in summary, they are about assessing what we have, any limitations or constraints we face, and whether a potential candidate will work with existing technologies in use in our project. The questions we can ask include (but are not limited to) the following:
  • Are you using SVGs in a specific context? For example, if your need is to display charts, then it might be preferable to use a library such as D3, rather than Snap.svg.

  • Are you making use of a library such as jQuery, and need to remove this dependency in favor of say plain JavaScript? If your ultimate need is to animate an SVG element, then Velocity.js may be worth considering.

  • Is support an issue? Some libraries offer commercial support, while others rely on a community effort; it can mean that bugs would be fixed, but this is reliant on people providing fixes that take time.

  • Does your project use an existing framework such as React, where an SVG library might have support for it as a plug-in?

Asking the right questions is not rocket science; the key is to be objective, and not be swayed by what we might like the sound of, or be tempted by a new feature in a library, if the rest of the library is not suitable for our needs. It’s important to realize that there is more than one way to crack a nut – if a library turns out not to be suited to our needs, then we can change to use a new one. However, this will take time – the more questions we can ask now, the less painful it will be later!

An Overview of Available Libraries

So – now we’ve set our hearts on using a library: where next, I hear you ask?

The power and flexibility of SVG means we could just use jQuery, which is a perfectly valid choice. However, there are a fair few libraries that are dedicated to SVG, or can easily be used with the format; these include the following:
  • Vivus – available from https://maxwellito.github.io/vivus/ , this library is great for producing line-drawn effects, as if we might sketch out a shape in 2D or 3D.

  • Paper.js – this library, described as being the Swiss Army Knife of vector graphics scripting, offers a large range of options. It’s available from http://paperjs.org/ and takes a different approach: it is a framework that runs on top of the HTML5 Canvas, using its own DOM and API to manipulate vector graphics.

  • Snap.svg - http://snapsvg.io/ ; this is arguably one of the more well-known libraries; its syntax is similar to jQuery, which makes it very easy to learn for those who already use this library.

  • SVG.js – downloadable from http://svgjs.com/ , this library doesn’t offer quite the same range and functionality as some of its bigger cousins; it makes up for this by staying as close to the SVG specification as possible, while being fast and lightweight.

  • D3.js – spend any time working with SVG and data manipulation, and you will soon come across this library (or one of the many that work on it, such as Raw.js). Available from https://d3js.org , this library is ideally suited to the visual display of data, such as line charts, stacked bars, or bubble charts.

  • Two – available from https://two.js.org/ , this library offers a 2D API, offering render-agnostic capabilities that allow the same API to operate in different contexts, such as SVG, WebGL, and Canvas.

  • Velocity JS – mention animation without using jQuery, and chances are you will hear of this library. Available from http://velocityjs.org/ , this offers a drop-in replacement for jQuery’s animation, using the best of jQuery and standard CSS animation code, and can easily be used with SVG.

There are a couple of other options that we’ve not included in this list but which nevertheless may be worth a look:
  • Raphaël has been available for some years and works well for much older browsers, such as IE5 or above. It’s available to download from http://dmitrybaranovskiy.github.io/raphael/ . Although still in use, its low barrier to entry (supporting browsers such as Chrome 5.0) made it difficult to support newer features so has been largely superseded by its replacement, Snap.svg.

  • Bonsai (available from https://bonsaijs.org ) is a lightweight SVG library that is still available for download. However a lack of updates since August 2014 and high level of unresolved issues makes it less attractive if you require any form of support – I would suggest looking at more recent alternatives that will provide better levels of support.

This list represents just a handful of some of the options available when using SVG. I would recommend spending time researching options online when it comes to choosing a library; the first one that comes up should not be the final solution, unless it turns out to be the closest fit for a project.

There are plenty of options available – to tempt you as a starter, we’re going to create some examples over the next few pages, to show you what is available, and how they operate when working with SVG. Our first example is a simple but intriguing library – how often have you seen images being drawn onscreen in real time, as if someone were drawing them in front of you?

Using Vivus to Draw SVG Images

Yes – I thought that last question might intrigue you: there is indeed such a library that can produce this effect!

Let me introduce you to Vivus – this simple library allows us to create this effect where elements appear to be hand-drawn on screen. Vivus comes in two flavors: a downloadable library (available from https://maxwellito.github.io/vivus/ ) or an online tool to create quick demos. We can apply this to all kinds of examples; for instance, we might use it to create button animations, such as the ones shown at https://codepen.io/iamryanyu/pen/XdQxmb .

A neat effect to replicate is hand-drawn text, in much the same way as we might sign a document – we’re going to use this as a basis for our next demo. To make it easier, we will avail ourselves of the Vivus Instant online tool – it’s a good starting point to create something we can later update using the library.

DRAWING WITH VIVUS

For our next demo, we’re going to use the Vivus Instant online tool, available at https://maxwellito.github.io/vivus-instant/ . This demo has a couple of prerequisites that we need to take care of first, so make sure you’ve done the following:
  • Installed Node.js (and NPM), if you haven’t already done so from previous exercises; this is required for the font conversion step.

  • We’re using the Dancing Script font available from Google Fonts at https://fonts.google.com/specimen/Dancing+Script . Feel free to substitute it for something else if you have it already installed. (We will go into this in more detail after the exercise.)

With these in place, let’s make a start:
  1. 1.

    We’ll start by extracting a copy of the Vivus folder from the code download that accompanies this book – go ahead and save it to our project folder.

     
  2. 2.

    Next, we need to install our conversion tool – for this, fire up a Node.js command prompt (or terminal session, for Mac users), then change to the working folder you downloaded in step 1.

     
  3. 3.
    At the prompt, enter this command, and press Enter:
    npm install --save text-to-svg

    NPM will install the text-to-svg tool; it will show a flashing prompt when this is completed.

     
  4. 4.
    With the tool now installed, we can go ahead with converting our font; for this, enter the following at the prompt and press Enter:
    node js/convert.js
     
  5. 5.

    Node.js will go away and convert the font into an SVG equivalent set of commands; when completed, copy and paste the text from the console window into a plain text file, and save as helloreader.svg in the img folder.

     

There is a copy of this in the code download; if you get stuck copying the file – it is labeled helloreader – example.svg.

  1. 6.

    At this stage, we can now animate it – for this, browse to https://maxwellito.github.io/vivus-instant/ , then drag and drop the image into the window.

     
  2. 7.

    You will see it appear onscreen – try changing the settings to see how it affects the image. For example, try changing the Duration value to 6000, and the Path timing function to Erase in out. Make sure you hit Update after any changes, to save them to the image!

     
  3. 8.

    When you are happy with your design, click on Download, and save the resulting image to the img subfolder under the Vivus folder as helloreader.svg.

     
  4. 9.

    We need to make one small change to it though, otherwise the SVG may appear clipped – go ahead and open the SVG in a text editor.

     
  5. 10.

    Look for the width="343.8" value in the first line of the code – increase it to 350.8, and save the file.

     
At this point, we can now preview the results – if all is well, you should see something similar to the screenshot shown in Figure 9-1.
../images/461821_1_En_9_Chapter/461821_1_En_9_Fig1_HTML.jpg
Figure 9-1

Animating text with Vivus.js

This is a great effect to add to any page, although it’s important not to go overboard in using it – this will end up destroying the effect you’re trying achieve! With this in mind, there are a few important points we should explore, so let’s take a moment to review the code in more detail.

Understanding How It Works

At first glance, you might be forgiven for thinking that this effect requires special magic; after all, we didn’t add any code when dropping our SVG image on the Vivus Instant site, so how does it all work?

Well, it relies on one simple principle – our shape must have a stroke (which can be dashed or solid) or border that we can animate. We’ve already met (and used) this attribute in earlier demos, but the trick here is not what we use, but how we use it. Let me explain:

If we take a close look at the screenshot shown in Figure 9-2, we can see the presence of stroke and fill attributes.
../images/461821_1_En_9_Chapter/461821_1_En_9_Fig2_HTML.jpg
Figure 9-2

An extract of the source code for our demo

These will, of course, not be present in standard text, so we added them in the conversion script; Vivus makes use of the stroke attribute to draw the required shape. The animation that creates this drawing effect is automatically added by Vivus Instant, as indicated in Figure 9-3.
../images/461821_1_En_9_Chapter/461821_1_En_9_Fig3_HTML.jpg
Figure 9-3

Example code produced by Vivus.js

The beauty about this is that we can easily extract this code and store it in a separate style sheet – although it may look a little odd, this is just how Vivus adds it; it is a standard keyframe-based animation. It’s up to us to decide whether we want to keep it inline (for instances such as creating company logos), or export it to a separate style sheet.

If you look carefully at the code in convert.js, you will see that we’ve used an .otf format font. We can use standard TTF fonts, but these produce a lot more SVG code; it’s worth converting it to OTF format! We can do it very quickly online, using the conversion facility at https://everythingfonts.com/ttf-to-otf .

Okay – let’s change tack: it’s time to revisit creating chart types. Remember how we looked at building standard pie or bar charts back in Chapter 8, “Creating Charts”? Well, they were just a few types of charts that we can building using SVG; there are plenty more that we can create – how about creating something different, using bubbles?

Creating Bubble Charts with D3

Okay – I’d better explain that little joke: hopefully it will become clear when I say we’re about to create bubble charts!

We’ve already explored several different ways to express data in chart form – this might be using a standard bar or pie chart, for example. However, we are not limited in our choice; there are dozens more available, which we can create by hand, but using a library will certainly make it easier for us.

The library I’m thinking of is D3.js – this has been designed for manipulating data that needs to be displayed visually on screen. It can handle bar or pie charts with ease, along with more exotic-sounding charts such as Voronoi tessellations, scatterplot matrices, and azimuthal projections, to name but a few. Fortunately we’re not going to do something as complicated as this; instead, let’s take a look at creating a straightforward bubble chart, using some imaginary data based on car manufacturers.

CREATING FORMS WITH D3

Let’s get cracking on our demo:
  1. 1.

    We’ll start by extracting a copy of the bubble folder from the code download that accompanies this book; go ahead and save this to our project folder. This sets up our basic style sheet, font, and various D3 libraries ready for use.

     
  2. 2.

    Next, open a new blank document, saving it as bubble.js in the html folder.

     
  3. 3.
    We can now add in our D3 code. There is a fair bit to go through, so we’ll break it down section by section, starting with our raw data:
    var json = {
      'children': [
        {'name': 'Ford', 'value': 60},
        {'name': 'Skoda', 'value': 34},
        {'name': 'Jaguar', 'value': 55},
        {'name': 'Seat', 'value': 29},
        {'name': 'Citroen', 'value': 20},
        {'name': 'Peugeot', 'value': 5},
        {'name': 'Volvo', 'value': 40}
      ]
    }
     
  4. 4.
    Leave a line, then add in these three variables – we’ll make use of these throughout our demo:
    var diameter = 1000, color = d3.scaleOrdinal(d3.schemeCategory10);
    var bubble = d3.pack().size([diameter, diameter]).padding(5);
    var margin = { left: 0, right: 100, top: 0, bottom: 0 }
     
  5. 5.
    We now get onto the important part: the SVG container. Go ahead and add the following lines in, to set it up:
    var svg = d3.select('#chart').append('svg')
      .attr('viewBox','0 0 ' + (diameter + margin.right) + ' ' + diameter).attr('width', (diameter + margin.right))
      .attr('height', diameter).attr('class', 'chart-svg');
     
  6. 6.
    Next up comes a little visualization: we’re using the D3 Hierarchy plug-in to convert our data into nodes before appending them to the chart:
    var root = d3.hierarchy(json).sum(function(d) { return d.value; });
    bubble(root);
     
  7. 7.
    With our nodes defined, let’s turn them into filled circles – for this, add the following lines:
    var node = svg.selectAll('.node')
      .data(root.children).enter()
      .append('g').attr('class', 'node')
      .attr('transform', function(d) { return 'translate(' + d.x + ' ' + d.y + ')'; }).append('g').attr('class', 'graph');
     
  8. 8.
    Our circles won’t mean a great deal, without at least some form of indication as to which bubble relates to which piece of data. We can do this (at least in part) by adding text labels:
    node.append("text")
      .attr("dy", "0.3rem").style("text-anchor", "middle")
      .style("font-size", "3rem").text(function(d) { return d.data.value; }).style("fill", "#ffffff");
     
  9. 9.
    Last, but by no means least, we need to add a legend so we know which color corresponds to which make of car:
    svg.append("g").attr("class", "legend").attr("transform", "translate(950,20)");
    var legend = d3.legendColor()
      .shape("path", d3.symbol().type(d3.symbolSquare).size(150)())
      .shapePadding(13).scale(color);
    svg.select(".legend").call(legend);
     
  10. 10.

    Save the file then open it in a browser to preview the results – if all is well, we will see the chart shown in Figure 9-4.

     
../images/461821_1_En_9_Chapter/461821_1_En_9_Fig4_HTML.jpg
Figure 9-4

Creating a Bubble chart

Hopefully you’ll agree that this is a little more interesting than a standard bar or pie chart! Although our demo is somewhat simplistic and limited in size, this will really come into its own with a much larger data set, such as comparing competitor size in a particular industry. No matter what the source of the data is though, the same principles apply – let’s take a look in more detail at what makes our demo tick.

Note

Much of the code has had to be compressed for reasons of space; if you need help, then please refer to bubble – finished version.js in the code download, for a view on how it should look.

Exploring Our Demo in Detail

For a simple demo, it sure looks like we’ve produced a lot of code! So how does it all work, to give us our bubble chart?

Well, we start with creating a JSON object that stores details of our data – this contains values for the car make and the number. We then assign a handful of variables, before using D3 to define our SVG container and apply it to the #chart element.

Next up, we use the D3 hierarchy to turn the values defined under json into nodes that we can insert into our bubble chart. As part of this, we use a transform method to move each circle into the right position. These circles are then appended using node.append, before being filled with a color from the D3 color scheme defined at line 13.

We then added text labels to each circle to identify which circle equates to which value. For each of these, we apply standard font attributes such as text-anchor, font-size and dy, to center each label in white to its appropriate circle. The last stage is to use the D3 legend plug-in to create our chart’s legend, and affix this to the page, with appropriate text labels as a key for our bubble chart.

Improving Our Design

Thinking further afield though, our design lacks impact – its simplicity actually makes it look like it punches with the weight of a featherweight boxer, whereas we want it to deliver more of a knockout blow!

There are several ways to do this, but two that come to mind are: add a little animation on displaying each bubble, and apply SVG filters to each of the bubbles in our chart. Yes, it seems ironic, but we can use SVG to enhance SVG!

For the former, we can simply add in some standard CSS animations – we need to specify one for each bubble, giving us seven in total. The first one would look like this:
.node:nth-child(1) .bubble {
  animation-delay: 0.075s;
}
…and the remaining six can be added in a similar fashion, increasing the delay value by 0.075s for each animation. We can then tie this into our demo using these rules:
.bubble {
  opacity: 0;
  animation: 1s forward animateIn
}
@keyframes animateIn {
  0% { opacity: 0; transform: scale(0.6) rotate(-15deg); }
  100% { opacity: 1; transform: scale(1) rotate(0); }
}
To really give our bubble chart some color, we can add in a filter effect for each bubble – there are a few considerations, such as type of filter, suitability, and so on. However the basic principle would require us to add in SVG code to define our filter, before adding a call to use it when appending each circle to our chart:
node.append("circle")
  .attr("r", function(d) { return d.r; })
  .style("filter", "url(#drop-shadow")
  .style("fill", function(d) {
    return color(d.data.name);
  });

To get a flavor for how we would add in the SVG filter, look for the bubble – with dropshadow.js file in the code. If you update the bubble.js link in the original demo to point to this file, you can see the effect in action.

Time for a change methinks – and to chart a new direction (oops, sorry!) We’ve only scratched the surface with regard to charting; for me, it’s all about trying different things, to see what works best for your needs.

Talking of trying things out – I love trying different effects; after all, one doesn’t learn if one doesn’t try, right? A great effect that I’ve discovered is Anime.js – this library provides a hand-drawn animation, which works beautifully with SVG images. To see what I mean, let’s dive in and take a look.

Getting Creative with Anime.js

When developing code, I frequently like to try different things out – it doesn’t matter what it is; I’ve played with all manner of different libraries and frameworks over the years!

One library that did pique my interest is the subject of our next demo – Anime.js. Available from http://animejs.com/ , it’s a fairly lightweight library, but it allows us to create a great effect: drawing an SVG image in real time, as if we were drawing it ourselves. We can use this for all kinds of situations though: How about adapting a range input to give the slider a little elasticity, for example? (Take a look at https://scotch.io/tutorials/build-an-elastic-range-input-with-svg-and-animejs , if you want to see just how anime.js is used…)

We’re going to do something that is a little simpler though – we will take an existing SVG and adapt it so that the borders appear as if we are drawing them in real time. I should warn you though: this exercise is a little fiddly, so patience is key – it will be worth it!

DRAWING SHAPES WITH ANIME: PART 1

For the purpose of this demo, we will use an SVG image from Free SVG Images (FSI), at https://​lovesvg.​com/​2018/​04/​theres-a-chance-this-is-wine-6275/​.

This exercise runs over a good few steps, so will come in two parts; the first part will set up the base markup and styles. We will cover the animation in the second part; don’t worry – there will be time to catch your breath before we move onto to start the second part.

Unfortunately, due to licensing restrictions, the SVG file is not available in the code download that accompanies this book; you will need to download it from the LoveSVG website.

Assuming we have our image downloaded, let’s make a start on updating our SVG image:
  1. 1.

    We’ll begin by extracting a copy of the anime folder from the code download that accompanies this book – go ahead and save it in our project folder.

     
  2. 2.

    Next, we need to download a copy of the image from the Love SVG site, – go ahead and save this in the anime folder.

     
  3. 3.

    We need to optimize the file, so browse to the online SVG optimizer at https://jakearchibald.github.io/svgomg/ , and drag and drop the file over the window (as we have done in previous exercises).

     
  4. 4.

    SVGO will automatically optimize the file; click on the Download arrow to save the file to the img folder in your project folder. Leave the file open but minimized for now – we will revert back to it shortly.

     

You may prefer to save it under a different name – if you do, then please adjust the next steps accordingly.

  1. 5.

    Next, revert back to the SVG file we created back in step 4, then copy and paste the contents of the SVG file into anime.html, replacing the comment <!—SVG CODE GOES IN AT THIS POINT --> in its entirety.

     
  2. 6.
    Take a careful look at the SVG code – you should see this line, near the start of the markup; remove it, including the <style> tags
    <style>.st5{fill:#1a1a1a}.st9{fill:#881b30}.st30{fill:#627c55}.st39{fill:#a09830}</style>
     
  3. 7.

    Go ahead and save the file; we can close it for now.

     

At this stage we now have most of our markup in place, but no JavaScript – that comes momentarily. This demo is a little fiddly, so now is a good time to pause for a few moments; go make yourself a cup of tea (or coffee?) and relax.

DRAWING SHAPES WITH ANIME: PART 2

The next part is where the fun really starts – we’re going to add in our JavaScript. If you’re ready to make a start, then let’s move on and finish our demo:
  1. 1.
    We’ll begin by creating a new file, then saving it as script.js in the js subfolder – go ahead and copy then paste in the following code:
    var capsText = anime({
      targets: '.capsText',
      strokeDashoffset: [anime.setDashoffset, 0],
      easing: 'easeInOutCubic',
      duration: 3000,
      complete: function(anim) {
        $(".capsText").css("fill", "#1a1a1a");
      },
      autoplay: true
    });
     
  2. 2.

    Repeat step 1 three more times, but in each instance, replace the highlighted values from step 1, with the values as indicated in Table 9-1.

     
Table 9-1

Values for the Anime Exercise

Instance Number

Property

Value

2

var

redText

 

targets:

.redText

 

fill:

#881b30

3

var

lineDrawing

 

targets:

.lineDrawing

 

fill:

#627c55

4

var

swirls

 

targets:

.swirls

 

fill:

#a09830

  1. 3.

    Save the file, and close it.

     
  2. 4.

    Now, revert back to our SVG image file – we need to edit our SVG, to add in stroke effects. For this, do a search for each instance of st5, then alter the code as indicated:

    class= "capsText" stroke="#1a1a1a" stroke-width="1"

     
  3. 5.

    Repeat step 3, but this time look for st9, and add in this code, as before:

    class= "redText" stroke="#881b30" stroke-width="1"

     
  4. 6.

    We have two more to update – the next one to look for is st30, and this time alter the code as shown:

    class= "lineDrawing" stroke="#881b30" stroke-width="1"

     
  5. 7.

    The last one to look for is each instance of st39 – go ahead and update the code as indicated:

    class= "swirls" stroke="#881b30" stroke-width="1"

     
  6. 8.
    Last but by no means least, go ahead and add a space after viewBox="30 90 432 432" in line 1, then add this in – this is to help keep the SVG to a more reasonable size:
    id="Calque" width=432 height=432
     
  7. 9.

    Go ahead and save the file, then preview the results in a browser –if all is well we will see our SVG design being drawn.

     

Phew – that was some exercise! We’ve covered a lot of steps; our demo has highlighted a useful technique we should master when working with SVG. The art of animated drawing looks complicated, but in fact is based on one simple key point – let’s take a moment to find out what that is, and what impact it has on our demo.

Dissecting Our Demo

There is something to be said for relaxing after a long day coding, in front of a log fire, with a nice glass of red wine – it sure takes a lot of beating! It’s perhaps no wonder that I would choose to animate an SVG centered on my favorite alcoholic beverage; it doesn’t matter though what the image looks like, as the same principles we used in the last two exercises can be applied to any SVG image.

The keen-eyed among you will likely spot that we're revisiting an effect we touched on in the Vivus demo – I suspect you might be (rightly) asking the reason for this, and there is a good one:

Although we're using the same effect in both cases, the tools we've used are different – Vivus is designed for animating SVGs, whereas anime.js is a JavaScript animation engine that can be used to animate all kinds of elements, including but not limited to SVGs. This is a perfect way to show just how different libraries can achieve the same effect, and that it is incumbent on us to choose the most appropriate one for our needs.

In both cases, the libraries depend on one property being present, as a minimum: stroke. Put simply, this can be seen as the SVG equivalent of border: 1px solid XXXXXXX (where XXXXXX is our chosen color). We can of course also add a stroke-width value to specify the thickness of our "border," or a stroke-dasharray to give our border a dashed effect, although these are not obligatory for the effect to work.

In the first part of this mega-exercise, we prepared our content – the first step was to optimize the image (which should become de facto when working with SVG), before exporting some inline styles to a separate window in Codepen. In the second part, we then dropped in four configuration objects, one each to represent the four classes that we've applied to the various paths specified in our code. We then finished off by adding in suitably colored stroke properties for each of the paths specified in our code, which were used by the Anime library to create the final solution.

Okay – let’s change tack and move on: Remember from earlier in the book, where we created some interesting effects using SVG filters? Well, for our next demo, we’re going to continue that theme, but take a different look at how we create our filters…this time using JavaScript!

Taking a Different Look at Filters

Cast your mind back, if you will, to Chapter 5, “Applying Filter Effects” – remember how we explored using CSS filters?

We saw how these were in reality just shorthand names for more exotic-sounding names such as feImage or feBlend; we can easily create a variety of different custom filters, but would typically apply them using standard CSS rules.

Is this the only way we can apply them? Of course not – we could if we wanted to, use JavaScript; this might involve changing classes, or applying them directly in code. Sure, this will work, but it’s not the cleanest way: is there an alternative? Absolutely – for those occasions where we might need to use JavaScript, there are a few libraries available that are dedicated to managing SVG filters; these include:
  • Filter Effects library – available from https://github.com/mkaemmerer/filter-effects , this library takes some of the manual grunt work out of creating the SVG markup, by using JavaScript to apply the core values and let the library compile these into fully fledged filter effects.

  • SVG-Filter – downloadable from http://mathisonian.github.io/svg-filter , this D3-based filter library allows us to apply filter primitive effects such as feTurbulence directly to an element; this gives us a really fine level of control over how an element is styled.

  • Philter – hosted at http://specro.github.io/Philter/ , this one takes a different approach; this allows us to control CSS filters using data-* tags, which are applied during post-processing.

  • Tiltshift.js – this library replicates a tilt-shift effect using data-* tags and standard CSS filters. It can be downloaded from http://www.noeltock.com/tilt-shift-css3-jquery-plugin/ .

One question I hear you ask though, which is why would we use such a library, when CSS works just as well? Ordinarily I would agree that CSS is a preferred option, but there may be instances where using a filter library might be more suited:
  • If you’re using an existing technology, such as D3, then at least one of the options in the list requires D3 as a dependency – you might prefer to simply extend the library;

  • Applying CSS filters will only show the shortcut names in our style sheet – some of these libraries show the full SVG filter markup, which gives us more control;

  • You may prefer to simply concentrate on applying markup to your content, and deal with styling as part of post-processing for your project. In this case, we could use the Philter library, which is designed for this purpose, rather than worrying about which CSS filters to apply.

There is one other library we’ve not mentioned in our list of possible options – that library is SVG.js. This has a filter plug-in that comes with the library and allows us to apply all manner of SVG filter effects, using a simple JavaScript syntax. To see how easy it is to apply, let’s knock up a quick demo using the plug-in – we’ll use it to apply a standard Gaussian blur effect to an image, as part of our next demo.

APPLYING FILTERS USING JAVASCRIPT

For our next demo, we will apply a simple Gaussian blur filter over an image from the Unsplash image library, which you can view at https://unsplash.com/photos/uwbajDCODj4 . It’s a very peaceful one of a Stockholm archipelago, taken by Anders Jildén – the principle we will use though can be applied to any image we need to use in our projects.

Let’s make a start on our demo:
  1. 1.

    We’ll begin by extracting a copy of the filter folder that is in the code download that accompanies this book; save this to our project folder.

     
  2. 2.
    Next, go ahead and create a new text file, saving it as filter.js in the js subfolder – add in the following code:
    var draw = SVG('drawing').size(500, 500);
    var image = draw.image('https://images.unsplash.com/photo-1498550744921-75f79806b8a7?fit=crop&fm=jpg&h=500&q=75&w=800')
    .size(500, 500);
    image.filter(function(add) {
      add.gaussianBlur(3, 0)
    });
     
  3. 3.

    Save the file – if we preview the results, we should see a very blurry photo, similar to the one shown in Figure 9-5.

     
../images/461821_1_En_9_Chapter/461821_1_En_9_Fig5_HTML.jpg
Figure 9-5

Applying a Gaussian filter

This was a really simple demo, to give you an idea of how easy it is to apply filters using the SVG.js filter plug-in. We could easily take it further by chaining together multiple filters, in much the same way as we might be using standard CSS. That aside, using JavaScript does afford us a couple of advantages, so without further ado, let’s take a look at the code in more detail.

Exploring the Code in More Detail

Although our code at first glance appears to be very simple, it hides a lot of the grunt work required to configure an SVG filter . To see what I mean, take a look at the code from our demo using a DOM inspector, and you will see something akin to the extract shown in Figure 9-6.
../images/461821_1_En_9_Chapter/461821_1_En_9_Fig6_HTML.jpg
Figure 9-6

Our Gaussianblur filter under the microscope

All of that markup was added from one line of code in our demo! It’s easy to see why using a library such as SVG.js is useful; we can concentrate on using the core effects such as Gaussian blur to re-create the effect that we need, without worrying about the markup. If you remember back as far as Chapter 5, “Applying Filter Effects, we had to create the SVG filter manually; this way, we can focus on creating the effect, then copy and paste the resulting markup into our code (and remove the plug-in) once we’ve achieved the desired effect.

The code we’ve used is very simple – we start with defining a new SVG object to the draw variable; this is used to create the SVG container we saw in Figure 9-6. Next up, we then draw our chosen image (in this case, the background image from the Unsplash library), in our SVG container, setting it at a size of 500px square. We then finish by applying a filter effect of GaussianBlur , using a (stdDeviation) value of 3.

The real beauty of this though is that we can manipulate the effects at a DOM level using JavaScript – if we were using plain CSS, then all we would be able to do is override an existing rule with a new one. If we were using JavaScript, we could run code such as this example:
var blur = document.getElementById("blur");
blur.setAttribute("stdDeviation", "5");

…if we wanted to dynamically change our filter effect at the point of triggering an event such as clicking a button or hovering over an image.

Thinking further afield though – SVG.js’ filter plug-in is perfect for creating some more advanced filter effects; one that comes to mind is the backdrop filter. It’s a great effect for removing some of the distraction if you have text overlaid on a busy image, for example – you can see it in use in a Codepen example I’ve created at https://codepen.io/alexlibby/pen/BxwzQb .

A word of warning – support for this filter is patchy with only Edge and Safari supporting it without requiring some form of flag to be enabled. Chrome will support it if the Experimental Web Platform features setting is enabled; Firefox doesn’t support it at present, but this is likely to change. It’s a good reason why SVG filters can be used to create this effect – the developer Vincent de Oliveira has created an example at https://codepen.io/iamvdo/pen/VLOGdw , which I think could be achieved using SVG.js!

If you want to really experiment with filters, then try installing the CSS filters console tool extension for Chrome: it’s available from https://github.com/spite/css-filters-devtools-extension and allows us to tweak filter settings directly in the browser.

Summary

When working with SVG as a medium, we can achieve a great deal using nothing more than a text editor and a little imagination; there are occasions though when we may need to resort to using a library to give us a little helping hand. Throughout the course of this chapter, we’ve touched on a few examples of what is available; let’s take a moment to review what we’ve learned.

We kicked off with a quick discussion on the merits of choosing a library, before taking a look at some of the options available and understanding why it pays to choose carefully. We then dived into a number of demos, starting with learning how to draw images using the Vivus library. We then explored how to create bubble charts using D3, before getting animated with the Anime.js library, and finally finishing with a different take on creating SVG filters using JavaScript.

Phew – it doesn’t seem a great deal, but we’ve certainly explored a few options! Our journey through the world of SVG continues apace; in the next chapter we will take things up a notch, by exploring some more real-world examples of what can be achieved using SVG.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.250.203