如何为svg虚线设置动画

时间:2017-07-15 11:29:40

标签: javascript jquery svg



var path = document.querySelector('.path');
	var length = path.getTotalLength();
	path.style.transition = path.style.WebkitTransition =
  	'none';
	path.style.strokeDasharray = length + ' ' + length;
	path.style.strokeDashoffset = length;
	path.getBoundingClientRect();
	path.style.transition = path.style.WebkitTransition =
  	'stroke-dashoffset 2s ease-in-out';
	path.style.strokeDashoffset = '0';

<svg  id="test" width="800px" height="369.643px" viewBox="0 0 800 369.643" enable-background="new 0 0 800 369.643">
	<path fill="none" 
  	stroke="#596E7A" stroke-width="10" stroke-miterlimit="10" stroke-dasharray="25,25" class="path" stroke-linecap="round"
	d="M34.762,225.595c25.084,109.862,211.31,151.786,342.262,108.929	c129.701-42.448,212.358-186.755,180.357-288.095C543.096,1.19,460.075-8.983,449.372,67.834 c-15.801,113.4,167.532,164.904,318.724,34.547"/>
	</svg>

	<svg width="800px" height="369.643px" viewBox="0 0 800 369.643" enable-background="new 0 0 800 369.643">
	<path fill="none" 
  	stroke="#596E7A"
	stroke-width="10"
	stroke-miterlimit="10"
	stroke-dasharray="25,25"
	stroke-linecap="round"
	d="M34.762,225.595c25.084,109.862,211.31,151.786,342.262,108.929	  c129.701-42.448,212.358-186.755,180.357-288.095C543.096,1.19,460.075- 8.983,449.372,67.834
	c-15.801,113.4,167.532,164.904,318.724,34.547"/>
	</svg>

     
&#13;
&#13;
&#13; 我得到了svg虚线。我想要动画虚线,但虚线已经变为实线。如何在顶部制作下线动画?

1 个答案:

答案 0 :(得分:0)

标准线条绘制技巧通过设置短划线图案的虚线偏移动画来实现。如果该行已经是虚线,则不能使用相同的技术。

一种简单的方法是用另一种与背景颜色相同的线覆盖你的线。然后设置动画,以显示其下方的虚线。

var path = document.querySelector('.path');
	var length = path.getTotalLength();
	path.style.transition = path.style.WebkitTransition =
  	'none';
	path.style.strokeDasharray = length + ' ' + length;
	path.style.strokeDashoffset = 0;
	path.getBoundingClientRect();
	path.style.transition = path.style.WebkitTransition =
  	'stroke-dashoffset 2s ease-in-out';
	path.style.strokeDashoffset = -length;
<svg width="800px" height="369.643px" viewBox="0 0 800 369.643" enable-background="new 0 0 800 369.643">
	<path fill="none" 
  	stroke="#596E7A"
	stroke-width="10"
	stroke-miterlimit="10"
	stroke-dasharray="25,25"
	stroke-linecap="round"
	d="M34.762,225.595c25.084,109.862,211.31,151.786,342.262,108.929	  c129.701-42.448,212.358-186.755,180.357-288.095C543.096,1.19,460.075-8.983,449.372,67.834
	c-15.801,113.4,167.532,164.904,318.724,34.547"/>

  <!-- white path that covers the first one -->
  <path fill="none" 
  	stroke="white" stroke-width="12" stroke-miterlimit="10" stroke-dasharray="25,25" class="path" stroke-linecap="round"
	d="M34.762,225.595c25.084,109.862,211.31,151.786,342.262,108.929	c129.701-42.448,212.358-186.755,180.357-288.095C543.096,1.19,460.075-8.983,449.372,67.834 c-15.801,113.4,167.532,164.904,318.724,34.547"/>
</svg>
  
  
<svg  id="test" width="800px" height="369.643px" viewBox="0 0 800 369.643" enable-background="new 0 0 800 369.643">
	</svg>