画面が表示されたら、図形をアニメーションさせる

画面が表示されたら図形が移動するサンプルを使って、GSAPの初期設定を学びます。
動作サンプルページ :画面が表示されたら、図形をアニメーションさせる
GSAPを読み込む
今回のサンプルでは、CDNを使って、リンクさせます。
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/gsap.min.js"></script>
動かすオブジェクトを指定
今回は、単純な四角形を用意し、それを動かします。また、CSSの値を変えることで、アニメーションさせます。
<style>
.container {
width: 400px;
height: 400px;
border: 1px #cccccc solid;
margin: 30px auto;
position: relative;
}
.box {
width: 40px;
height: 40px;
background-color: #d17575;
position: absolute;
top: 20px;
left: 20px;
}
</style>
<div class="container">
<div class="box"></div>
</div>
GSAPの設定
最初にオブジェクトを動かす関数を用意し、画面の読み込みが終わったら、その関数を実行させます。
GSAPには、いろいろな使い方が用意されていますが、今回は、最初に設定された値からアニメーションさせる「to」を用います。
gsap.to();
最初に、変化させるオブジェクト、今回はclass「box」を指定します。
gsap.to(".box");
次に、変化させたいプロパティを、カンマ区切りで追加します。
gsap.to(".box", {
top: "300px",
left: "300px",
});
最後に、アニメーションさせる秒数を、「duration」で指定します。単位は秒で指定します。
gsap.to(".box", {
top: "300px",
left: "300px",
duration: 3,
});
コード
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>画面が表示されたら、図形をアニメーションさせる</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/gsap.min.js"></script>
<script>
function move() {
gsap.to(".box", {
top: "300px",
left: "300px",
duration: 3,
});
}
window.onload = move;
</script>
<link rel="stylesheet" href="css/reset.css">
<style>
.container {
width: 400px;
height: 400px;
border: 1px #cccccc solid;
margin: 30px auto;
position: relative;
}
.box {
width: 40px;
height: 40px;
background-color: #d17575;
position: absolute;
top: 20px;
left: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>