Tutorial

Animating More Elements Along SVG Paths with JavaScript (Part 2)

Draft updated on Invalid Date
Default avatar

By Luis Manuel

Animating More Elements Along SVG Paths with JavaScript (Part 2)

This tutorial is out of date and no longer maintained.

Introduction

In a previous tutorial we introduced a new library that allows us to animate elements along an SVG path called PathSlider. In addition, we put into practice the use of this library and developed a simple slider, with a minimum of effort. In this tutorial, we will see two more examples that illustrate the potentialities of our library and the SVG paths in general.

For example, we have developed another slider using a closed SVG path as in the previous tutorial, but with some extra elastic effects:

Elastic Slider

https://codepen.io/lmgonzalves/pen/bvpLyW/

We also wanted to do something a little more original, and we created a full screen and responsive slider of images, using this time an open SVG path, generated automatically with JavaScript:

Images Slider

https://codepen.io/lmgonzalves/pen/EEKEaM/

As you can see, the first of these sliders is very similar to the one in the previous tutorial, we have only added some elastic effects to give it a special touch. So in this tutorial, we will focus on developing the slider of images. However, the code of this first slider can also be found in the GitHub repository.

So, let’s start developing this interesting images slider!

HTML Structure

The HTML code for our images slider will be even simpler than the one used for the other two sliders. Let’s see:

<!-- Path Slider Container -->
<div class="path-slider">
    <!-- Slider items -->
    <a href="#" class="path-slider__item path-slider__item--1"><div class="item__circle"></div></a>
    <a href="#" class="path-slider__item path-slider__item--2"><div class="item__circle"></div></a>
    <a href="#" class="path-slider__item path-slider__item--3"><div class="item__circle"></div></a>
    <a href="#" class="path-slider__item path-slider__item--4"><div class="item__circle"></div></a>
    <a href="#" class="path-slider__item path-slider__item--5"><div class="item__circle"></div></a>
</div>

As you can see, this time we have not defined the SVG path in our HTML code. That is because we will generate it from the JavaScript code, something that will allow us greater flexibility, adapting the SVG path to the dimensions of the screen.

Adding Styles

As this time our slider will be full screen, we must add some necessary styles:

// This slider will be full screen
// The `background-image` will be set using JavaScript
.path-slider {
  position: relative;
  width: 100%;
  height: 100%;
  background-position: center;
}

// We also need this extra element (generated with JavaScript) to fade the images smoothly
.path-slider__background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-position: center;
}

And the images corresponding to each of the elements of the slider have been defined in this way:

// Defining images

.path-slider__item--1 .item__circle {
  background-image: url("../images/img1.jpg");
}

// ... More `background-image` definitions for each item

Please note that we have not emphasized the styles needed for the elements to be centered on the SVG path, and the other general styles used. If you have any doubts about it you can take a look at the previous tutorial, and of course, you can also see the full code in the GitHub repository.

So let’s see how to bring our slider to life!

Get it working with JavaScript

The first thing we will do is insert the SVG path element that we need to move the slider items through it:

// Creating SVG and path elements and insert to DOM

var svgNS = 'http://www.w3.org/2000/svg';
var svgEl = document.createElementNS(svgNS, 'svg');

var pathEl = document.createElementNS(svgNS, 'path');
// The `getSinPath` function return the `path` in String format
pathEl.setAttribute('d', getSinPath());
pathEl.setAttribute('class', 'path-slider__path');

svgEl.appendChild(pathEl);
document.body.appendChild(svgEl);

As you may have noticed, we have generated the path using the getSinPath function, which is responsible for returning the path in String format taking into account the dimensions of the screen and some other parameters. We have decoupled this function in a separate file for a better organization, and you can see its implementation, as well as a brief description of the available options, in the GitHub repository.

Now let’s see the code for getting the images of the slider items that we have defined in the CSS code, and also the code needed to smoothly switch the images every time we select an item:

// Changing `background-image`
// Firstly, saving the computed `background` of each item, as these are defined in CSS
// When item is selected, the `background` is set accordingly

var items = document.querySelectorAll('.path-slider__item');
var images = [];
for (var j = 0; j < items.length; j++) {
    images.push(getComputedStyle(items[j].querySelector('.item__circle')).getPropertyValue('background-image'));
}

var imgAnimation;
var lastIndex;
var setImage = function (index) {
    if (imgAnimation) {
        imgAnimation.pause();
        sliderContainer.style['background-image'] = images[lastIndex];
        sliderContainerBackground.style['opacity'] = 0;
    }
    lastIndex = index;
    sliderContainerBackground.style['background-image'] = images[index];
    imgAnimation = anime({
        targets: sliderContainerBackground,
        opacity: 1,
        easing: 'linear'
    });
};

Then we need to add the extra element needed to fade the images smoothly, and also set the image for the initial current item (the first one):

var sliderContainer = document.querySelector('.path-slider');
var sliderContainerBackground = document.createElement('div');
sliderContainerBackground.setAttribute('class', 'path-slider__background');
setImage(0);
sliderContainer.appendChild(sliderContainerBackground);

And having all the above ready, we can initialize our slider with this simple piece of code:

// Initializing the slider

var options = {
    startLength: 'center',
    paddingSeparation: 100,
    easing: 'easeOutCubic',
    begin: function (params) {
        // Item get selected, then set the `background` accordingly
        if (params.selected) {
            setImage(params.index);
        }
    }
};

var slider = new PathSlider(pathEl, '.path-slider__item', options);

As we explained in the previous tutorial, by default the PathSlider library adds event listeners for click events, so we don’t have to worry about that. All we have to do is to switch the images properly, using the setImage function.

Finally, to get the path adapting to the dimensions of the screen, thus achieving a responsive behavior, we just have to regenerate the SVG path and update items position on resize event:

// Regenerate the SVG `path` and update items position on `resize` event (responsive behavior)

window.addEventListener('resize', function() {
    pathEl.setAttribute('d', getSinPath());
    slider.updatePositions();
});

This way, our slider will look great in every screen size.

Conclusion

And we are done! We have put into practice once again the possibilities offered by the SVG paths to develop attractive and functional components.

Please go ahead and check the live demos

Play with the code on CodePen

We really hope you have enjoyed the tutorial and that it has been useful!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Luis Manuel

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel