Fluid Simulator
by ElijahCirioli
HTML
<canvas id="myCanvas" width="600" height="350" style="border:2px solid #000000;"></canvas>
JavaScript
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var count = 10;
var radius = 4;
var viscosity = 0.5;
var softness = 0.5;
var gravity = 1;
var framerate = 60;
var particles = [];
var width = canvas.width;
var height = canvas.height;
function Particle(x, y) {
this.x = x;
this.y = y;
particles.push(this);
}
Particle.prototype.distance = function(p2) {
return Math.sqrt(Math.pow(p2.x - this.x, 2) + Math.pow(p2.y - this.y, 2));
}
Particle.prototype.canMove = function(newX, newY) {
if (newX + radius > width || newX - radius < 0 || newY + radius > height || newY - radius < 0) {
return false;
}
for (var i = 0; i < particles.length; i++) {
if (this.distance(particles[i]) < 2 * radius && particles[i] !== this) {
return false;
}
}
return true;
}
function update() {
for (var i = 0; i < particles.length; i++) {
var p = particles[i];
//gravity
if (p.canMove(p.x, p.y + gravity)) {
p.y += gravity;
}
}
render();
}
function render() {
context.fillStyle = "white";
context.fillRect(0, 0, width, height);
for (var i = 0; i < particles.length; i++) {
context.fillStyle = "#67CAEB";
context.beginPath();
context.arc(particles[i].x, particles[i].y, radius, 0, 2 * Math.PI);
context.fill();
}
}
document.onclick = function(e) {
var rect = canvas.getBoundingClientRect();
var mouseX = Math.round(e.clientX - rect.left);
var mouseY = Math.round(e.clientY - rect.top);
particles.push[new Particle(mouseX, mouseY)];
update();
}
var thread = setInterval(update, 1000 / framerate);