Here we must notice the changed move method.
export class Umo {
constructor(canvas, color) {
this.canvas = canvas;
// this.x = this.canvas.getWidth() / 2;
this.x = 0;
this.y = 0;
this.r = 3;
this.dx = 1;
this.color = color;
}
draw() {
this.canvas.getContext().beginPath();
this.canvas.getContext().fillStyle = this.color;
this.canvas.getContext().arc(this.x, this.y, this.r,
0, Math.PI * 2,
false);
this.canvas.getContext().fill();
this.canvas.getContext().closePath();
}
move() {
if (this.x + this.dx > this.canvas.getWidth()
|| this.x + this.dx < 0)
this.dx = -this.dx;
this.x += this.dx;
// a(x-h)^2 + k where h is offset to right, k is offset up
// http://www.intmath.com/plane-analytic-geometry/4-parabola.php
this.y = Math.pow(this.x - 200, 2) / 100;
// this.toString(); // for debugging
if (this.y > this.canvas.getHeight())
this.dx *= -1;
}
toString() {
let s = '';
s += this.x + ':' + this.y;
return s;
}
};
animate001.js
'use strict';
import {Canvas} from './nmlCanvas.js';
import {Umo} from './nmlUmo001.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();
umo.draw();
}
}
const repeater = function () {
setInterval(redraw, 20);
}
const go = function () {
canvas = new Canvas('canvas', '#ffff88');
let c = new Umo(canvas, '#000088');
console.log(c.toString());
arr.push(c);
repeater();
}
window.addEventListener('load', go);
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Canvas Test Animation, Parabolic Trajectory</title>
<script type='module' src='animate001.js'></script>
</head>
<body>
<section>
<canvas id='canvas' width='400' height='400'>
If you see this text, your browser is very old.
</canvas>
</section>
</body>
</html>
See it live: Click here!