Animate SVG on hover with relative target

355 Views Asked by At

Using Anime.js I want to morph an SVG on hover. I can make this work fine with one, but am having trouble figuring out how to make the same script apply to multiple elements on the page. JSFiddle

<a class="link" href="#">
  <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100">
    <path class="shape-from" fill="#000000" d="M21.062 21.062H78.94V78.94H21.06z"/>
    <path class="shape-to" fill="#000000" d="M65.62 67.548l-44.558 11.39L32.858 37.41l46.08-16.348z"/>
    <path class="shape-morph" fill="#000000" d="M21.062 21.062H78.94V78.94H21.06z"/>
  </svg>
</a>

So when you hover over .link it should get the child .shape-morph and animate it to the value of .shape-to. Then the reverse on mouseleave.

$('.link').mouseenter(function() {
  var shapeMorph = $(this).find('.shape-morph');
  var shapeTo = $(this).find('.shape-from').attr('d');
  anime({
    targets: shapeMorph,
    d: shapeTo,
    easing: 'easeOutElastic',
    duration: 1000
  });
});
$('.link').mouseleave(function() {
  var shapeMorph = $(this).find('.shape-morph');
  var shapeFrom = $(this).find('.shape-from').attr('d');
  anime({
    targets: shapeMorph,
    d: shapeFrom,
    easing: 'easeOutElastic',
    duration: 1000
  });
});

Another issue I have is that when it does morph there is a weird flicker occasionally, anyone know how to fix this?

1

There are 1 best solutions below

0
On

I needed to put mouseenter/mouseleave inside an each and send the correct target and path through functions: JSFiddle

var path1 = 'M21.062 21.062H78.94V78.94H21.06z'
var path2 = 'M35.062 21.062H60.94V78.94H21.06z'

function animateMe(el, path) {
  anime.remove(el);
  anime({
    targets: el,
    d: path,
    easing: 'easeOutElastic',
    duration: 1000
  });
};

function enterLink(el, path) {
  animateMe(el, path2);
};

function leaveLink(el, path) {
  animateMe(el, path1);
};

$('.link').each(function() {
  $(this).on('mouseenter', function(e) {
    enterLink($(this).find('.shape-morph').get(0));
  });
  $(this).on('mouseleave', function(e) {
    leaveLink($(this).find('.shape-morph').get(0));
  });
});