Reputation: 43
previous arc needs to disappear and only the recent one should show up.
Here is the code I have until now.
context.fill();
context.closePath();
}
})(document);
function randomColor() {
var color = [];
for (var i = 0; i < 3; i++) {
color.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + color.join(',') + ')';
}
<canvas id="testCanvas" style="border:1px solid #000000;"></canvas>
Upvotes: 1
Views: 60
Reputation: 17644
Here is how to do it:
Here is a working sample:
(function(doc) {
var canvas = doc.getElementById("testCanvas");
var context = canvas.getContext("2d");
var circles = []
function drawCircle(circle) {
context.beginPath();
context.fillStyle = circle.color;
context.arc(circle.x, circle.y, circle.rad, 0, 2 * Math.PI, true);
context.fill();
context.closePath();
}
function collision(circle1, circle2) {
var dx = circle1.x - circle2.x
var dy = circle1.y - circle2.y
return Math.sqrt(dx * dx + dy * dy) < (circle1.rad + circle2.rad);
}
function drawCircles(data) {
context.clearRect(0, 0, canvas.width, canvas.height);
drawCircle(data)
for (var i = circles.length - 1; i >= 0; i--) {
if (collision(circles[i], data)) {
circles.splice(i, 1);
} else {
drawCircle(circles[i])
}
}
circles.push(data)
}
// click event handler
canvas.onclick = function(e) {
drawCircles({
color: randomColor(),
rad: 5 + Math.random() * 30,
x: e.clientX - e.target.offsetLeft,
y: e.clientY - e.target.offsetTop
})
}
})(document);
function randomColor() {
var color = [];
for (var i = 0; i < 3; i++) {
color.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + color.join(',') + ')';
}
<canvas id="testCanvas" style="border:1px solid #000000;"></canvas>
To make it interesting I made the new circle with a random radius...
If you want to make things even more interesting (and have the time for it) instead of making the overlapping circles disappear, make them move & shrink until they do not overlap.
Upvotes: 2