Dots follow demo
DEmonstration of following dots
by Victor Melnik
HTML
<div id="panel">
<canvas id="canvas" width="400" height="300"></canvas>
</div>
CSS
input[type="range"] {
width: 50%;
}
input[type="text"] {
width: 75px;
}
#panel {
width: 250px;
height: 250px;
}
JavaScript
// Инициализация
var canv = new Canv(canvas.getContext('2d'),
canvas.width, canvas.height);
// Начальные координанты объектов
var ax = rand(canvas.width);
var ay = rand(canvas.height);
var bx = rand(canvas.width);
var by = rand(canvas.height);
var speed = 10;
canvas.addEventListener('mousemove', function(e) {
// Обработчик событий перемещения мыши
var rect = canvas.getBoundingClientRect();
bx = e.clientX - rect.left;
by = e.clientY - rect.top;
}, false);
var timer = setInterval(function() {
// Основа алгоритма, описание ниже
var angle = Math.atan2(by - ay, bx - ax);
if (angle < 0) angle += 2 * Math.PI;
if (Math.abs(by - ay) <= speed &&
Math.abs(bx - ax) <= speed) {
ax = bx;
ay = by;
} else {
ax += speed * Math.cos(angle);
ay += speed * Math.sin(angle);
}
canv.clear();
canv.drawCircle(ax, ay, '#0e0');
canv.drawLine(ax, ay, angle, 'black')
canv.drawCircle(bx, by, '#e00');
}, 50);
function rand(max) {
return Math.floor(Math.random() * max);
}
// Обёртка для канваса
function Canv(ctx, w, h) {
this.radius = 5;
this.clear = function() {
ctx.fillStyle = 'white';
ctx.rect(0, 0, w, h);
ctx.fill();
};
this.drawCircle = function(x, y, color) {
ctx.strokeStyle = "#000";
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, this.radius, Math.PI * 2, false);
ctx.stroke();
ctx.fill();
ctx.closePath();
};
this.drawLine = function(x, y, deg, color) {
ctx.strokeStyle = color;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + Math.cos(deg) * 2 * this.radius,
y + Math.sin(deg) * 2 * this.radius);
ctx.stroke();
ctx.closePath();
};
}