JavaScriptを使用してHTMLアニメーションを作成する方法を学びます。
JavaScriptでHTMLアニメーションを作成する方法を示すために、簡単なWebページを使用します:
<!DOCTYPE html>
<html>
<body>
<h1>My First
JavaScript Animation</h1>
<div id="animation">My animation will go here</div>
</body>
</html>
Try it Yourself »
すべてのアニメーションは、コンテナ要素に関連している必要があります。
<div id ="container">
<div id ="animate">My
animation will go here</div>
</div>
コンテナ要素はstyle = "position: relative"で作成する必要があります。
アニメーション要素はstyle = "position: absolute"で作成する必要があります。
#container {
width: 400px;
height:
400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height:
50px;
position: absolute;
background: red;
}
Try it Yourself »
JavaScriptのアニメーションは、要素のスタイルの段階的な変化をプログラムすることによって行われます。
変更はタイマによって呼び出されます。 タイマ間隔が小さいと、アニメーションは連続して見えます。
基本的なコードは次のとおりです:
var id = setInterval(frame, 5);
function frame() {
if (/*
test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
function myMove() {
var elem =
document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos ==
350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
Try it Yourself »