Simplest way to draw an SVG path

2019-05-06 13:21发布

I tried the following tutiroal from here: http://jakearchibald.com/2013/animated-line-drawing-svg/

var path = document.querySelector(".svg1");
var length = path.getTotalLength();
path.style.transition = path.style.WebkitTransition = "none";
path.style.strokeDasharray = length;
path.style.strokeDashoffset = length;
path.getBoundingClientRect();
path.style.transition = path.style.WebkitTransition = "stroke-dashoffset 1s ease-out";
path.style.strokeDashoffset = 0;

HTML is as following:

<path class="svg1" 
style="fill: none; stroke: #3498db; stroke-width: 7; stroke-linecap: round; stroke-linejoin:  miter; stroke-miterlimit: 4;"
d="M247 103 A130 130 0 1 1 247 363 A130 130 0 1 1 247 103"
/>

The thing is when I use it in Firefox, it works. But if I go for Chrome, the animation freezes at something like 75% and instantly jumps to 100% in like 30s. I've noticed, that the animation doesn't freeze only in one case - if I use stroke-dashoffset 530ms ease-out, i.e. 530ms or less.

Could someone suggest a solution for that or recommend a good way to animate an svg path without tons of useless code?

1条回答
再贱就再见
2楼-- · 2019-05-06 13:51

CSS-Tricks recently wrote an article on this:

The idea is we set our SVG shape with a dashed stroke where the dash length is the length of the entire path. Then we offset each dash with that path length with an animation. (Read the article)

FIDDLE

.svg1 {
  stroke-dasharray: 822;
  stroke-dashoffset: 822;
  animation: dash 5s linear alternate infinite;
}
@keyframes dash {
  from {
    stroke-dashoffset: 822;
  }
  to {
    stroke-dashoffset: 0;
  }
}
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="500px" height="500px" viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">
  <path class="svg1" style="fill: none; stroke: #3498db; stroke-width: 7; stroke-linecap: round; stroke-linejoin:  miter; stroke-miterlimit: 4;" d="M247 103 A130 130 0 1 1 247 363 A130 130 0 1 1 247 103" />
</svg>

So how do you get the length of the path?

That's also covered in the above article:

Just run the code:

var path = document.querySelector('.svg1');
var length = path.getTotalLength();
查看更多
登录 后发表回答