0

I have a group of two.js shapes. When a user hovers over a shape, I want that one shape to spin.

http://merhoo.github.io/secrets.html

Issue with css animations: if I apply a :hover animation to the svg shapes, it affects the position of the shape somehow, moving it to the top left corner.

So I'm trying to bind a mouseover event to each child for them to spin.

var shapes = makeFlowers();

for (var r = 0; r < rows; r++) {
  for (var c = 0; c < cols; c++) {
    ...
    var shape = pickFlower();
    shape.translation.set(hi * two.width, vi * two.height);
    two.add(shape);
  }
}
two.update();

for (var f in flowers) {
  var flower = flowers[f];
  $(flower._renderer.elem)
    .click(function(e) {
      flower.fill = "blue";
    })
}

So how do you apply hover/mouseover animations to shapes in two.js?

merhoo
  • 589
  • 6
  • 18

1 Answers1

0

Two issues (haha) with adding individual event handlers/animations to two.js objects.

  1. The first I don't understand still: it will only add the event handler to the last shape in the loop. Maybe because it is rendered in the html as one svg, the onclick is applied to either one or all the paths. Seems like a bug on Two.js' part.
  2. As mentioned in this post, transforming the path of an SVG via an animation is very heavy for the browser. If you apply the animation to the container of the SVG, it won't be applying a transformation to each point in the path.

Solution:

  1. Make a div for each row, and fill it with a div for each cell

    for (var r = 0; r < rows; r++) {
      var rowId = "row" + r;
      var row = $("<div/>").addClass("row").attr("id", rowId).appendTo('body');
      for (var c = 0; c < cols; c++) {
        var cellId = "cell" + ((r * rows) + c);
        $(row).append('<div class="cell" id="' + cellId + '"></div>');
      }
    }
    
  2. For each cell, make an instance of Two, add the shape to that

    $(".cell").each(function (index, object) {
      var two = new Two({
        width: size + padding,
        height:size + padding
      }).appendTo(object);
      var shape = pickFlower(shapes);
      shape.translation.set(two.width / 2, two.height / 2);
      two.add(shape);
      two.update();
    });
    
  3. Add the hover animation to the divs with CSS

    .cell:hover {
      animation: loaderAnim 5s ease-in-out infinite normal forwards;
      padding: 0;
      margin: 0;
    }
    
    
    @keyframes loaderAnim {
      0% {
        transform:rotate(0deg);
      }
      50% {
        transform:rotate(90deg);
      }
      100% {
        transform:rotate(0deg);
      }
    }
    

Notes:

  • Don't try to combine making the div and adding Two to the div. The div may not be added to the html, and it will then add multiple two instances to a div, and other funky things
merhoo
  • 589
  • 6
  • 18