More Animation Examples

Two Moving Objects

Example 12.4. Animating Two Separate Objects, the HTML5
<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Canvas Test Animation</title>
        <script type='module' src='animate000.js'></script>
    </head>
    <body>
        <section>
            <canvas id='canvas' width='400' height='300'>
                If you see this text, your browser is very old.
            </canvas>
        </section>
    </body>
</html>

See it live: Click here!


Example 12.5. animate000.js
'use strict';
import {Canvas} from './nmlCanvas.js'
import {Umo} from './nmlUmo0.js'

var c0;
var c1;
var canvas;

const redraw = function () {
    canvas.clear();         // clear canvas
    canvas.prep();          // prep canvas with background color
    c0.move();              // move thing ie change coordinates
    c0.draw();              // draw thing
    c1.move();              // move thing ie change coordinates
    c1.draw();              // draw thing
}

const repeater = function () {
    setInterval(redraw, 10);
}

const init = function () {
    canvas = new Canvas('canvas', '#ffff88');
    c0 = new Umo(canvas, '#000088');
    c1 = new Umo(canvas, '#cc0000');
    repeater();
}

var nml = window.addEventListener('load', init);

Several Moving Objects

Example 12.6. Animating n Objects, the HTML5

Here we place the objects in an array for indurstrialization.

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Canvas Test Animation</title>
        <script type='module' src='animate000a.js'></script>
    </head>
    <body>
        <section>
            <canvas id='canvas' width='400' height='300'>
                If you see this text, your browser is very old.
            </canvas>
        </section>
    </body>
</html>

See it live: Click here!


Example 12.7. animate000a.js
'use strict';
import {Canvas} from './nmlCanvas.js'
import {Umo} from './nmlUmo0.js'

var arr = [];
var canvas;

const redraw = function () {
    canvas.clear();     // clear canvas
    canvas.prep();      // prep canvas with background color
    for (let umo of arr) {
        umo.move();  // change coordinates
        umo.draw();  // draw again with new coordinates
    }
}

const repeater = function () {
    setInterval(redraw, 10);
}

const moveit = function () {
    canvas = new Canvas('canvas', '#ffff88');
    let c0 = new Umo(canvas, '#000088');
    arr.push(c0);
    c0 = new Umo(canvas, '#cc0000');
    arr.push(c0);
    c0 = new Umo(canvas, '#009900');
    arr.push(c0);
    c0 = new Umo(canvas, '#003300');
    arr.push(c0);
    repeater();
}

window.addEventListener('load', moveit);