16
13

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.

SVGのパスに沿ってDOMを動かす

Posted at

デモはこちら↓↓。
svgのパスに沿ってdomを動かす
スクリーンショット 2016-04-30 20.48.31.png

svgのpathの全長は path.getTotalLength(); で、
そのpathのとある地点(position)の座標は path.getPointAtLength(position); で取得できることを利用し、ループ関数内で以下のようにして動かします。

1. positionの値を増加させ、path.getPointAtLength(position);で座標を取得
2. 取得した座標を元に、absoluteさせているDOMのtopとleftを指定
3. positionの値がgetTotalLength();の値を越していたらpositionの値を初期化

main.js
var circle = document.getElementById("circle");

var path = document.getElementById("my-path");
var pathLength = path.getTotalLength(); // pathの全長を取得
    
var nowPos = 0;

anime(); // ループを実行

function anime() {
        
    if(nowPos > pathLength) {
        nowPos = 0; // 現在の座標がpathの全長を越していたら0に初期化
    }
        
    var point = path.getPointAtLength(nowPos); // path上のとある地点の座標を取得
    circle.style.left = point.x-15 + "px";
    circle.style.top = point.y-15 + "px";
    nowPos++;
   
    setTimeout(function() { anime(); }, 1000/120);
}

16
13
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
16
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?