Dotted Wow Effects: About Magic in Simple Words



    We continue to watch techniques for creating various animations in the interfaces. We have already become acquainted with particles , masks, and changing the shapes of various objects - the time has come to draw dotted lines.

    Before moving on to the article, I will make a small digression. This series of articles is intended for developers (primarily beginners) who want to do beautiful things, but are completely confused in complex tools. Each time we touch upon one method of using one or another instrument and look at the creation of any effects that can be applied. Comments that “it was better at the time of the flash” or that “you need to draw animations in AfterEffects” certainly have a right to exist, but they will be taken out of context and will not help beginners in solving their problems.

    Back to the topic. SVG elements have a set of properties that contain the word stroke - a stroke. These properties allow us to make any line dotted. First of all, we will be interested in the following properties:

    • stroke
    • stroke-width
    • stroke-linecap
    • stroke-dasharray
    • stroke-dashoffset

    The stroke property allows you to specify the color of the lines, stroke-width - their thickness, stroke-linecap allows you to specify a style for rounding the ends of the line. Usually we use either the default value (there are no roundings) or the value round (rounding in the shape of a circle). In the examples you can see both options.

    These three properties are not particularly difficult to understand, but the remaining ones are best taken apart.

    Stroke-dasharray




    This property usually causes the greatest difficulty for beginners. At first glance, especially on a curved line, it is completely not clear what values ​​influence (and there can be many). But in fact, everything is very simple.

    Imagine a dash line. We start to look at him from the beginning. It has strokes and spaces. They alternate. Bar, space, bar, space, etc. Now imagine a sequence of lengths. Say 8mm, 2mm, 8mm, 2mm, etc. As written in GOST. It turns out that we have a cycle of 2 values. 8mm always falls on a stroke, 2mm - on a space.

    If we did not know about the standard and used our sequence of 5mm, 5mm, 5mm, 5mm, then there would be a cycle of one value. 5mm would hit both the bar and the space bar.

    And you can take a long cycle, say 1mm, 5mm, 20mm (similar values ​​are in the illustration). Then the matches will go in a longer sequence: 1mm - stroke, 5 - space, 20 - stroke, 1 - space, 5 - stroke, 20 - space, and again 1 - stroke. That's it, the cycle is closed.

    For those who want to quickly play with this property, I will leave a link to the sandbox .

    Stroke-dashoffset




    The stroke-dashoffset property is needed in order to shift the dashed line relative to the line along which it follows. In the example, it goes along line segments, so the result that gives this property is quite obvious. The main thing to remember about the sign of the displacement - intuitively, it may seem that the plus and minus are mixed up.

    Another sandbox for those who want to try.

    These two properties were created in order to simply make the lines dotted, but we will use them not quite in this form. It can be said that it’s not quite as intended. Perhaps this is the fact that prevents some developers from remembering about some tools at the time of solving the problem - it seems to them that this tool is not intended for such work. But, as we know, in some cases a microscope is the best tool for driving nails.

    One Touch Preloader




    You have probably already seen similar animations. This fragment is spinning in a circle, square or some other curve. Now we are interested in the insides of this example. If in a nutshell, then we need a closed curve line. We will use the square to simplify our calculations, but the general methods will work with any curves.


    The length of one side of the square is 80. The perimeter is 320. This is the length of the line on which everything will happen. If it was a complex hand-drawn path, then we would know in advance what length it got there. The fragment that we will spin in a circle will also have a length of 80. This is not tied to the length of the side of the square, just a coincidence. It remains 320 - 80 = 240. Returning to the dotted line context, we can say that 80 is a stroke, 240 is a space:


    Little life hack:
    It can often be convenient to take large spaces (so that the sum of the numbers in the stroke-dasharray is longer than the length of the curve) so as not to clog your head with counts when animating one fragment on an open curve.
    Since the line is closed, we can offset it all with stroke-dashoffset and it will seem that the fragment is spinning in a circle.

    anime({
        targets: '. . .',
        strokeDashoffset: -320, // меняем значение
        easing: 'linear',
        duration: 1000,
        loop: true
    });


    We continue ...


    Sooner or later, the preloader should come to the state when the process, the end of which we were waiting for, was completed. It would be nice not just to remove the preloader, but to show the user that everything is fine, everything has ended. One option is to transform it into a check mark.



    For such transitions, two curves are usually taken - one for the preloader, the other for the final animation. We will add path:


    Please note this is not a pure check mark, it is part of the square + check mark. It is good to hide the transition from one curve to another with the help of their partial overlap. A fragment moves in a square, reaches a certain point, we hide the square and show the second curve with exactly the same fragment in the same place where it was before the transition. Further, a new fragment already moves along a new curve, but it seems to us that the trajectory of the original fragment has changed.

    let finish = anime({
        targets: 'ok',
        strokeDashoffset: -84,
        autoplay: false
    });
    let animation = anime({
        targets: 'loader',
        strokeDashoffset: -320,
        loop: true,
        run: (anim) => {
            if (loadingCompleted && anim.progress > 60 && anim.progress < 61) {
                anim.pause();
                document.getElementById('loader').style.display = 'none';
                document.getElementById('ok').style.display = 'block';
                finish.play();
            }
        }
    });

    Animation of stroke-dasharray does not work very well in certain browsers (I will not point my finger at IE), so I have to get by with animation of stroke-dashoffset. The initial stroke-dashoffset value for the new curve is calculated based on the length of the new fragment. Its length (142) minus the length of the initial (80) = displacement (62).


    Tru underline


    We often use underscores for various elements. This is a good way to label interaction with something other than color. Many people don’t even think that something interesting can be done with underscores.

    The first example is the usual horizontal menu. It is on every second site. We will slightly vary the effect of underlining the active element of this menu.



    Immediately pay attention to the markup:


    Adding SVG doesn't break it much. So this technique as a whole can be applied when finalizing an existing layout. Values ​​of 20, 80 turned out, as you might guess, from 100. This is the length of the line. We have five elements, and only one needs to be emphasized. 100/5 = 20, and 80 remains on a large, large gap. Further, a technical matter (index is the number of the menu item to which you want to move the underline):

    anime({
        targets: '. . .',
        strokeDashoffset: [-(100 / 5) * index],
        stroke: `hsl(${ (index * 360 / 5) % 360 }, 100%, 50%)`
    });

    It remains only to do this when you mouse over or focus from the keyboard on the elements. I think you should not tell how this is done. In the example, the animation is automated for easy viewing.


    Mega underline




    If the previous example is already fed up with many, this one is not there yet. The general idea is the same as in the previous example, just the elements are located one below the other, and the line is a little curved.


    As you can see, the markup is not very complicated. After a little stylization of all this, we can draw a path, knowing what size ratios are in our form. In the same way we find the length of the fragment that will move. And then we hang up the focus / blur handler with our movement:

    email.addEventListener('focus', () => {
        anime({
            targets: '. . .',
            strokeDashoffset: 0
        })
    });


    Scrollll ...


    We all scroll. Every day, many times. Sometimes we see scrolling through the pages, slow or horizontal ... I once saw it all in one bottle. Horror. But there are less destructive effects for the psyche that look good on the landing pages, which we scroll from beginning to end, most likely only once. I am talking about the lines that pursue us. They can be tied to performing some kind of action, presenting services or scrolling, as in our example.

    First we need to draw the line itself. We do not have content, so its form is not so important - it is not attached to anything.



    Then we will rotate it to a vertical position and place it on the page. The most important thing here is to monitor the location of the content and the length of the SVG element itself so that nothing goes in different directions. Such things are always unique, so it’s difficult to give some universal recommendations on this subject.



    In technical terms, there will be nothing new. We simply bind the value of stroke-dashoffset to the scroll:

    window.addEventListener('scroll', () => {
        let d = document.body.offsetHeight / path.getTotalLength();
        let offset = -Math.floor(window.pageYOffset / d) + 50;
        anime({
            targets: '. . .',
            strokeDashoffset: [offset],
            duration: 0
        });
    });

    The result is quite interesting.


    You can just draw too




    Of course, it is worth mentioning that you can simply draw lines. We make a stroke the length of the entire curve and the same long space, and then shift this long-long dotted line to the length of the curve. The effect is the usual line drawing.


    This example also changes the color of the letters, but these are just details. The most important thing here is drawing curves.

    You can still get the entertaining effect of crawling worms or just a mishmash of lines moving in a random direction.



    We draw a curve-curve line, make a dotted line and move it. Nothing complicated, everything is the same as in the previous examples. The sandbox uses CSS animations to implement the movement, but keep in mind that IE has problems integrating such animations and SVGs, so use JS and everything will be fine.


    Conclusion


    Dotting is not a very difficult activity, but nevertheless it should be mastered and applied on occasion, without loading your brain with inventing crutches and complex solutions, where you can do without them.

    Also popular now: