Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Like https://generativeartistry.com/tutorials/circle-packing/
- // but without the sillyness of iteratively growing by one unit
- // then checking for collision, as the maximum radius
- // allowed by borders or each other circles is already known.
- var canvas = document.querySelector('canvas');
- var context = canvas.getContext('2d');
- var size = window.innerWidth;
- var dpr = window.devicePixelRatio;
- canvas.width = size * dpr;
- canvas.height = size * dpr;
- context.scale(dpr, dpr);
- context.lineWidth = 2;
- var circles = [];
- var minRadius = 2;
- var maxRadius = size/2;
- var totalCircleAttempts = 500;
- for( var i = 0; i < totalCircleAttempts; i++ ) {
- var newCircle;
- var circleSafeToDraw;
- newCircle = {
- x: Math.floor(Math.random() * size),
- y: Math.floor(Math.random() * size),
- radius: maxRadius
- }
- // Check if new circle center spawned inside another
- var isInside = false;
- for(var i = 0; i < circles.length; i++) {
- var otherCircle = circles[i];
- var d = otherCircle.radius;
- var x = newCircle.x - otherCircle.x;
- var y = newCircle.y - otherCircle.y;
- if (d*d >= (x*x) + (y*y)) {
- isInside = true;
- break;
- }
- }
- if(isInside) {
- continue;
- }
- // Reduce the radius if too close to an edge
- if(newCircle.x - newCircle.radius <= 0)
- newCircle.radius = newCircle.x;
- if(newCircle.x + newCircle.radius >= size)
- newCircle.radius = size - newCircle.x;
- if(newCircle.y - newCircle.radius <= 0)
- newCircle.radius = newCircle.y;
- if(newCircle.y + newCircle.radius >= size)
- newCircle.radius = size - newCircle.y;
- // Reduce the radius if too close to another circle
- for(var i = 0; i < circles.length; i++) {
- var otherCircle = circles[i];
- var d = newCircle.radius + otherCircle.radius;
- var x = newCircle.x - otherCircle.x;
- var y = newCircle.y - otherCircle.y;
- if (d*d >= (x*x) + (y*y)) {
- newCircle.radius = Math.sqrt((x*x) + (y*y)) - otherCircle.radius;
- }
- }
- // Don't draw too small circles
- if(newCircle.radius<minRadius) {
- continue;
- }
- // Draw the new circle
- circles.push(newCircle);
- context.beginPath();
- context.arc(newCircle.x, newCircle.y, newCircle.radius, 0, 2*Math.PI);
- context.stroke();
- }
Advertisement
Add Comment
Please, Sign In to add comment