Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="wrap">
	<canvas class="canvas" id="canvas_bubble"></canvas>
</div>
<div class="btn_wrap"><button class="btn" id="render_bubble">render bubble</button></div>
              
            
!

CSS

              
                html,body{
	padding:0;
	margin:0;
	height:100%;
}
.wrap{
	height:60%;
	background:rgba(140,140,140,0.5);
	text-align:center;
}

.canvas{
	height:100%;
	width: 100%;
	background:#e8e8f0;
}
.btn_wrap{
	text-align:center;
}
.btn{
	width: 120px;
	height:30px;
	background:#abb;
	border:none;
	outline:none;
	-webkit-tap-highlight-color: #999;
	margin:10px 5px;
}
              
            
!

JS

              
                window.CP.PenTimer.MAX_TIME_IN_LOOP_WO_EXIT = 6000;
var gCount = 0;
class CanvasBubbleChart {
	constructor(args) {
		args = args || {};
		this.canvas = document.querySelector(args.canvas);
		if (!this.canvas) {
			console.log("need canvas");
			return;
		}
		this.ctx = this.canvas.getContext("2d");
		this.pixelRatio = window.devicePixelRatio || 1;
		// init canvas size
		this.canvas.width =
			this.pixelRatio * parseInt(getComputedStyle(this.canvas).width);
		this.canvas.height =
			this.pixelRatio * parseInt(getComputedStyle(this.canvas).height);
		this.circle_r = Math.min(
			this.canvas.width / 2 - 30,
			this.canvas.height / 2 - 30
		);

		this.iterations = args.iterations
			// ? args.iterations < 0 ? 0 : args.iterations
			// : 2;
		this.time = args.time ? args.time : 500;
		this.density = args.density ? args.density : 0.5;

		// init bubbles
		if (args.bubbles && args.bubbles.length > 0) {
			this.initBubbles(args.bubbles);
		}

		this.drawBubbles = this.drawBubbles.bind(this);
	}

	initBubbles(bubbles) {
		let w = this.canvas.width;
		let h = this.canvas.height;
		let radius = this.circle_r;
		let len = bubbles.length;

		// compute scale factor K for radius
		let weight_sum = 0;
		bubbles.forEach(ele => {
			weight_sum += ele.weight * ele.weight;
		});
		let K = Math.sqrt(this.density * radius * radius / weight_sum);
		this.K = K;
		let max_radius = -1;

		// compute radius again and init object's dataset
		this.bubbles = bubbles.map(ele => {
			// init center for bubble
			let center_x = w / 2 - radius + Math.random() * 2 * radius;
			let center_y = h / 2 - radius + Math.random() * 2 * radius;
			let distance = Math.sqrt(
				Math.pow(w / 2 - center_x, 2) + Math.pow(h / 2 - center_y, 2)
			);
			let r = ele.weight * K;
			r = r < 4 ? 4 : r; // r >= 4
			if (r > max_radius) {
				max_radius = r;
			}
			if (distance > radius - r) {
				// move center into circle
				center_x += (w / 2 - center_x) * (distance - radius + r) / distance;
				center_y += (h / 2 - center_y) * (distance - radius + r) / distance;
			}
			return {
				weight: ele.weight,
				color: ele.color,
				radius: r,
				x: center_x,
				y: center_y
			};
		});

		this.max_radius = max_radius;
		// compute position for bubbles
		this.computePosition();
	}

	renderBubble(bubbles) {
		if (bubbles && bubbles.length > 0) {
			this.initBubbles(bubbles);
		}
		// draw bubbles
		this.start_time = +new Date();
		this.speed = this.max_radius / this.time;
		this.drawBubbles();
	}

	computePosition() {
		let iterations = this.iterations;
		console.log('iterations', iterations)
		let iteration = 0;
		let bubbles = this.bubbles;
		let len = bubbles.length;
		let startTime = +new Date();
		while (iteration < iterations) {
			iteration++;
			let l_1 = len;
			while (l_1--) {
				// duff's device save much time, but almost ineffective when two duff Nested
				this.traverseBubbles(bubbles[l_1]);
			}
		}
		console.log('gCount', gCount, +new Date() - startTime)
	}

	traverseBubbles(bubble1) {
		let bubbles = this.bubbles;
		let len = bubbles.length;
		let count = (len / 8) ^ 0;
		let start = len % 8;
		while (start--) {
			this.divideBubbles(bubble1, bubbles[start]);
		}
		while (count--) {
			this.divideBubbles(bubble1, bubbles[--len]);
			this.divideBubbles(bubble1, bubbles[--len]);
			this.divideBubbles(bubble1, bubbles[--len]);
			this.divideBubbles(bubble1, bubbles[--len]);
			this.divideBubbles(bubble1, bubbles[--len]);
			this.divideBubbles(bubble1, bubbles[--len]);
			this.divideBubbles(bubble1, bubbles[--len]);
			this.divideBubbles(bubble1, bubbles[--len]);
		}
	}

	divideBubbles(bubble1, bubble2) {
		gCount++;
		if (
			bubble1.color === bubble2.color &&
			bubble1.radius === bubble2.radius &&
			Math.abs(bubble1.x - bubble2.x) < 0.001
		) {
			return;
		}
		let diff = this.collisionCheck(bubble1, bubble2);
		if (diff > 0) {
			return;
		}
		diff = Math.abs(diff);
		let cta = Math.atan(
			Math.abs(bubble1.y - bubble2.y) / Math.abs(bubble1.x - bubble2.x)
		);
		let x_diff = diff * Math.cos(cta) + 0.2;
		let y_diff = diff * Math.sin(cta) + 0.2;

		// pos analyze
		if (bubble2.x >= bubble1.x && bubble2.y >= bubble1.y) {
			// 4 quadrant
			bubble2.x += x_diff;
			bubble2.y += y_diff;
		} else if (bubble2.x <= bubble1.x && bubble2.y >= bubble1.y) {
			// 3 quadrant
			bubble2.x -= x_diff;
			bubble2.y += y_diff;
		} else if (bubble2.x <= bubble1.x && bubble2.y <= bubble1.y) {
			// 2 quadrant
			bubble2.x -= x_diff;
			bubble2.y -= y_diff;
		} else if (bubble2.x >= bubble1.x && bubble2.y <= bubble1.y) {
			// 1 quadrant
			bubble2.x += x_diff;
			bubble2.y -= y_diff;
		}
	}

	collisionCheck(bubble1, bubble2) {
		var x = Math.abs(bubble1.x - bubble2.x);
		var y = Math.abs(bubble1.y - bubble2.y);
		var r = bubble1.radius + bubble2.radius;
		return Math.sqrt(x * x + y * y) - r;
	}

	drawBubbles() {
		let now = +new Date();
		let scale = (now - this.start_time) * this.speed;

		let bubbles = this.bubbles;
		let ctx = this.ctx;
		let len = bubbles.length;
		ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

		let count = (len / 8) ^ 0;
		let start = len % 8;
		while (start--) {
			this.drawBubble(bubbles[start], scale);
		}
		while (count--) {
			this.drawBubble(bubbles[--len], scale);
			this.drawBubble(bubbles[--len], scale);
			this.drawBubble(bubbles[--len], scale);
			this.drawBubble(bubbles[--len], scale);
			this.drawBubble(bubbles[--len], scale);
			this.drawBubble(bubbles[--len], scale);
			this.drawBubble(bubbles[--len], scale);
			this.drawBubble(bubbles[--len], scale);
		}

		if (now < this.start_time + this.time) {
			window.requestAnimationFrame(this.drawBubbles);
		} else if (this.speed !== 0) {
			this.speed = 0;
			window.requestAnimationFrame(this.drawBubbles);
		}
	}

	drawBubble(bubble, scale) {
		let ctx = this.ctx;
		let radius = bubble.radius;
		ctx.fillStyle = bubble.color;
		
		ctx.beginPath();
		if (scale < radius && this.speed !== 0) {
			ctx.arc(bubble.x, bubble.y, scale, 0, 2 * Math.PI);
		} else {
			let damp = this.speed === 0 ? 0 : (scale - radius) / this.max_radius;
			let spring = 2 * Math.exp(-8 * damp) * Math.sin(2 * 2 * Math.PI * damp);
			ctx.arc(bubble.x, bubble.y, radius + spring, 0, 2 * Math.PI);
		}
		ctx.fill();
	}
}

var createDataset = function() {
	var dataset = [];
	for (var i = 0; i < 300; i++) {
		dataset.push({
			weight: Math.floor(200 * Math.random()),
			color: "rgba(" +
				Math.floor(Math.random() * 240) +
				"," +
				Math.floor(Math.random() * 240) +
				"," +
				Math.floor(Math.random() * 240) +
				"," +
				(0.5 + 0.5 * Math.random()) +
				")",
			opacity: 0.5 + 0.5 * Math.random()
		});
	}
	return dataset;
};

var bubbleChart = new CanvasBubbleChart({
	canvas: "#canvas_bubble",
	bubbles: createDataset(),
	iterations: 2,
	time: 1200,
	density: 0.3
});


document.querySelector("#render_bubble").addEventListener("click", () => {
	bubbleChart.renderBubble();
});

              
            
!
999px

Console