Random Particle In A Circle
by wio_dude
HTML
<canvas id="canvas" width="500" height="350"></canvas>
JavaScript
function randomPoint(circle) {
var angle = Math.random() * 2 * Math.PI;
point = {
x: circle.x + circle.radius * Math.cos(angle),
y: circle.y + circle.radius * Math.sin(angle)
};
return point;
}
function drawCircle(ctx, circle) {
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.radius, 0, 2*Math.PI);
ctx.stroke();
}
function moveTo(circle, point) {
circle.x = point.x;
circle.y = point.y;
}
var BOUNDARY = {
x: 175,
y: 175,
radius: 150
};
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var particle = {
x: 100,
y: 100,
radius: 10
};
var loop = setInterval(function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveTo(particle, randomPoint(BOUNDARY));
drawCircle(ctx, BOUNDARY);
drawCircle(ctx, particle);
}, 1000);