JavaScript HTML DOM Animation

❮ 前章へ 次章へ ❯

JavaScriptを使用してHTMLアニメーションを作成する方法を学びます。


基本的なWebページ

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 */ 
    }
}

JavaScriptを使用してアニメーションを作成する

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 »

❮ 前章へ 次章へ ❯