snap svg切换动画

时间:2016-05-27 16:49:55

标签: javascript animation svg snap.svg

我正在使用Snap.svg创建一个动画图标,可在搜索和X点击之间切换。我让动画向一个方向发展。我知道它可能会使用回调函数来切换回来,但我没有足够的经验让它正常工作。

JSFiddle



//Creates Snap object

var paper = Snap("#search");


//Creates lines

var top = paper.path("M42.5,104.7L98.3,44c0,0,8.9-11.2,21.2-2.5c17.5,12.3,19.2,56-7.7,66.4c-6.8,2.7-12.7-3.2-12.7-3.2L80.8,85.7l0,0c-4,4.3-9.7,6.9-16.1,6.9c-12.2,0-22.1-9.9-22.1-22.1c0-1.3,0.1-2.6,0.3-3.9").attr({fill:"none", strokeWidth:"10px", stroke:"#b7b7b7",strokeLinecap:"round", strokeLinejoin:"round", strokeMiterlimit:"10", strokeDashoffset:"0",strokeDasharray:"80, 220"});

var bottom = paper.path("M43,66.7c1.8-10.3,10.9-18.2,21.7-18.2c12.2,0,22.1,9.9,22.1,22.1c0,5.8-2.3,11.1-5.9,15.1c0,0-16.9,15-49.8,4.3C9.8,83.2,5.8,57.3,17.1,46.4C30.8,32.9,42,45.6,42,45.6l57.2,59.3").attr({fill:"none", strokeWidth:"10px", stroke:"#b7b7b7",strokeLinecap:"round", strokeLinejoin:"round", strokeMiterlimit:"10",strokeDashoffset:"81",strokeDasharray:"80, 220"});


//Animates on click

paper.click(function(){Snap.animate(0,-200, function(value){top.attr({'strokeDashoffset': value })},300, mina.easein );});

paper.click(function(){Snap.animate(0,-300, function(value){bottom.attr({'strokeDashoffset': value })},300, mina.easein);});




1 个答案:

答案 0 :(得分:0)

最简单的解决方案可能只涉及在两种不同的状态之间切换。我的实现看起来像:

var toggle = true;

paper.click(function() {
  if (toggle) {
    toggleTo();
    toggle = false;
  } else {
    toggleFrom();
    toggle = true;
  }
});

function toggleTo() {
  Snap.animate(0,-200, function(value){top.attr({'strokeDashoffset': value })},300, mina.easein );
  Snap.animate(0,-300, function(value){bottom.attr({'strokeDashoffset': value })},300, mina.easein);
}

function toggleFrom() {
  Snap.animate(-200, 0, function(value){top.attr({'strokeDashoffset': value })},300, mina.easein );
  Snap.animate(-300, 81, function(value){bottom.attr({'strokeDashoffset': value })},300, mina.easein);
}

首先,我将布尔变量toggle设置为true。然后在你创建的SVG的click事件中,我检查元素所处的状态(基于布尔值),然后调用相应的函数来为SVG设置动画。

修改:Here's the JSFiddle.

Here's a similar Stack Overflow question.