5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Snap.svgでホバーアニメーションを要素ごとにやってみる。

Posted at

Snap.svg触ってみています。
というかSVG自体ほぼ初めてです。

知り合いエンジニアの方に教えてもらったのですが、ここのサイト(Snap.svgの使い方まとめ)が良いみたいなので参考にして書いてみています。

要素ごとにアニメーションさせたい

こんな感じで四角を作って、各要素ごとにアニメーションさせたいです。

svg.js
  var paper = Snap(200,200).remove().attr({viewBox: [0,0,200,200]});
  var rect = [];
  
  rect[0] = paper.rect(10,10,30,30).attr({fill:"red"});
  rect[0].mouseover(function(e){
    rect[0].attr({fill: "blue"});
  });
  rect[0].mouseout(function(e){
    rect[0].attr({fill: "red"});
  });
  
  rect[1] = paper.rect(10,50,30,30).attr({fill:"red"});
  rect[1].mouseover(function(e){
    rect[1].attr({fill: "blue"});
  });
  rect[1].mouseout(function(e){
    rect[1].attr({fill: "red"});
  });

  }
  
  rect[2] = paper.rect(10,90,30,30).attr({fill:"red"});
  rect[2].mouseover(function(e){
    rect[2].attr({fill: "blue"});
  });
  rect[2].mouseout(function(e){
    rect[2].attr({fill: "red"});
  });

  }
  
  var container = document.querySelector("#container");
  paper.prependTo(container);

for文でまとめたら'attr' of undefinedって怒られた。

こんな感じにしたら Uncaught TypeError: Cannot read property 'attr' of undefinedと怒られました。

svg.js
  var paper = Snap(200,200).remove().attr({viewBox: [0,0,200,200]});
  var rect = [];

  for(var i = 0; i < 3; i++){
    var y = 10 + i * 40;
    rect[i] = paper.rect(10,y,30,30).attr({fill:"red"});

    rect[i].mouseover(function(e){
      rect[i].attr({fill: "blue"});
    });
    
   	rect[i].mouseout(function(e){
     rect[i].attr({fill: "red"});
    });
  }
  
    var container = document.querySelector("#container");
  paper.prependTo(container);

#イベント発火時はthisを使うと上手くいった

rect[i].attr()this.attr()に変更すると上手くいきました。

    rect[i].mouseover(function(e){
      this.attr({fill: "blue"});
    });

    rect[i].mouseout(function(e){
      this.attr({fill: "red"});
    });

thisの参照がかわるみたいですね。

Snap.svg便利っぽいのでもう少し触ってみます。

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?