I draw 100 canvases of different sizes on a canvas, and they should not intersect. these circles will also animate from right to left (turning back to the right edge of the canvas when they leave the screen), and will also have a vertical “bob” for them, which also cannot cross other circles.
Below I am trying to attempt to block the browser. I scroll through a collection of circles and perform a function detectOverlap(), passing it a collection of circles.
Then the function detectOverlap()goes in circles, performing the following check:
detectOverlap: function (bubblesArr) {
while (true) {
var hit = 0;
for (var i=0; i<bubblesArr.length; i++) {
var circle = bubblesArr[i];
var dx = this._x - circle._x;
var dy = this._y - circle._y;
var rr = this._radius + circle._radius;
if (dx * dx + dy * dy < rr * rr) {
hit++;
}
}
if (hit == 0) {
break;
}
this._x = Math.round(Math.random() * this.stage.getWidth());
this._y = Math.round(Math.random() * this.stage.getHeight());
}
},
if hit == 0, the loop breaks, and we assume that there are no overlaps. Otherwise, we arbitrarily calculate the new X / Y position and restart the process.
. - ?
( ):
"", , .
var $container;
var listData;
var bubbles = [];
function init(l, c) {
$container = c;
listData = l;
var stage = new Konva.Stage({
container: $container.selector,
width: window.innerWidth,
height: 500
});
layer = new Konva.Layer();
for (var i=0; i<listData.length; i++) {
bubbles[i] = new celebApp.Bubble.Bubble(listData[i], stage);
}
for (var i=0; i<bubbles.length; i++) {
bubbles[i].detectOverlap(bubbles);
}
for (var i=0; i<bubbles.length; i++) {
var b = bubbles[i];
layer.add(new Konva.Circle({
x: b._x,
y: b._y,
radius: b._radius,
fill: b._fill,
stroke: b._stroke,
strokeWidth: b._strokeWidth,
}));
}
stage.add(layer);
}
Bubble:
, , . , .
var Bubble = function (listData, stage) {
this.stage = stage;
this._x = Math.round(Math.random() * stage.getWidth()),
this._y = Math.round(Math.random() * stage.getHeight()),
this._radius = Math.round(Math.random() * 80);
this._fill = 'red';
this._stroke = 'black';
this._strokeWidth = 4;
this._speed = 3;
};
Bubble.prototype = {
detectOverlap: function (bubblesArr) {
while (true) {
var hit = 0;
for (var i=0; i<bubblesArr.length; i++) {
var circle = bubblesArr[i];
var dx = this._x - circle._x;
var dy = this._y - circle._y;
var rr = this._radius + circle._radius;
if (dx * dx + dy * dy < rr * rr) {
hit++;
}
}
if (hit == 0) {
break;
}
this._x = Math.round(Math.random() * this.stage.getWidth());
this._y = Math.round(Math.random() * this.stage.getHeight());
}
},
};
EDIT: @MarcB - . , 100 while()?
for (var i=0; i<bubblesArr.length; i++) {
var circle = bubblesArr[i];
var combinedRadius = Math.abs(circle._radius + this._radius);
var distance = Math.abs(this._x - circle._x);
if (distance <= combinedRadius) {
hit++;
}
}