jQueryのanimateメソッドでfill、strokeが使えない時【SVG】
まずはSVGの用意。
Illustratorで使いたいデータをSVG形式で保存して、保存したものをテキストエディットなどで開くとコードが出てくるのでそれをHTMLにコピペ。
もしくは保存するときに[SVGコード]というのが出てくるのでそれをクリックしても見れる。
HTML
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 352.51 226.45"> <polygon class="cls-1" points="113.46 120.8 119.98 105.41 113.46 90.01 136.3 108.21 113.46 120.8"/> <polygon class="cls-1" points="238.3 90.01 231.78 105.41 238.3 120.8 215.46 108.21 238.3 90.01"/> <path class="cls-1" d="M337.65,165.28s-94.78-11.4-161.39,41.32c-66.62-52.72-161.39-41.32-161.39-41.32L0,176.46l176.25,50,176.25-50Z"/> <path class="cls-1" d="M307.94,114.27a99.75,99.75,0,0,0-9.36-42l-.33-.72C278.48,29.6,230.56,0,174.55,0,118.76,0,71,29.35,51.08,71l0,0V71a99.21,99.21,0,0,0-3.35,78.67L83.6,126.86,72.79,108.29C89.45,88.82,111.71,72.46,137.11,64l28.46,37.67-21.33,33.11,31.69,17.72L211,134.79,187.4,101.68l29.92-35.76c24,9.17,44.87,25.34,60.55,44.24l-8.81,16.7,32.25,22.68c0,.06.05.12.07.18l0-.1.15.1,0-.46A99.24,99.24,0,0,0,307.94,114.27ZM171.58,136.35l-12.32-6.28,8.37-13,4,5.12Z"/> </svg>
CSS(scss)
今回jQueryでストロークのアニメーションを動かすので、CSSのみで動かすkeyframeは使わない。IE8,9が非対応だから使うにしてもアレだ・・・
svg{ width:50%; margin:50px auto; display:block; polygon,path{ fill: none; stroke: #ccc; stroke-width: 2; stroke-dasharray: 1000; stroke-dashoffset: 1000; /* cssのみで動かす場合 IE8,9非対応 -webkit-animation: strokeanime 1s linear forwards; animation: strokeanime 1s linear forwards; */ } } /* cssのみで動かす場合 IE8,9非対応 @-webkit-keyframes strokeanime { to { stroke-dashoffset: 0; } } @keyframes strokeanime { to { stroke-dashoffset: 0; } } */
jQuery
重要なのがこのColor.hook。通常ではstroke、fillは使えないのでこれを書き足せば使えるようになる。
jQuery.Color.hook( "stroke fill" ); var $svganime = $("svg polygon,svg path"); $svganime.animate({ "strokeDashoffset":0 },{ duration:2000, easing:'linear', complete:function(){ $(this).animate({ "fill":"#1FCDD3", "stroke":"#1FCDD3" },500,"linear"); } });
See the Pen SVG by inoma (@inoma) on CodePen.