анимация Point
by Qwerty_Wasd
HTML
<canvas></canvas>
JavaScript
class Point {
constructor(x, y, rel, vel, ctx){
this.x = x;
this.y = y;
this.ctx = ctx;
this.velX = vel;
this.velY = vel;
this.rel = rel || {x: 0, y: 0};
}
move() {
if(this.x > 200) this.velX = -this.velX;
if(this.x < 0) this.velX = this.velX * (-1);
if(this.y > 100) this.velY = -this.velY;
if(this.y < 0) this.velY = this.velY * (-1);
this.x += this.velX;
this.y += this.velY;
}
render() {
this.ctx.fillRect(this.x, this.y, 10, 10);
this.ctx.beginPath();
this.ctx.moveTo(this.x + 5, this.y + 5);
this.ctx.lineTo(this.rel.x + 5, this.rel.y + 5);
this.ctx.stroke();
}
}
let ctx = document.querySelector('canvas').getContext('2d');
let point1 = new Point(3,100, this, 2, ctx);
let point2 = new Point(10,10, point1, 2, ctx);
let point3 = new Point(140,20, point2, 2, ctx);
function loop() {
ctx.clearRect(0,0,600,600);
point1.render();
point2.render();
point3.render();
point1.move();
point2.move();
point3.move();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);