Random Particle Painting
Creates painting from particle that moves randomly and changes color randomly.
by wio_dude
HTML
<canvas id="canvas" width="500" height="350"></canvas>
CSS
canvas {
border: 1px solid black;
}
JavaScript
function var_dump(name, x) {
var elem = document.getElementById("var-" + name);
if (typeof elem === "undefined" || elem === null) {
var body = document.getElementsByTagName("body")[0];
var elem = document.createElement("div");
elem.id = "var-" + name;
body.appendChild(elem);
}
elem.innerHTML = x;
}
function pad(s) {
if (s.length < 2) {
return "0" + s;
}
return s;
}
function Color(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
}
Color.prototype.toString = function() {
return "#" + pad(this.r.toString(16)) + pad(this.g.toString(16)) + pad(this.b.toString(16));
}
function Sprite(id, x, y, radius) {
this.id = id;
this.x = x;
this.y = y;
this.radius = radius;
this.color = new Color(0,0,0);
}
Sprite.prototype.update = function(ctx) {
var newTs = new Date().getTime();
var timeElapsed = 0;
if (typeof this.lastTs !== "undefined") {
timeElapsed = newTs - this.lastTs;
}
this.lastTs = newTs;
var_dump(this.id, timeElapsed + "ms " + this.toString());
var oldStyle = ctx.fillStyle;
ctx.fillStyle = this.color.toString();
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
ctx.fill();
ctx.fillStyle = oldStyle;
};
Sprite.prototype.toString = function() {
return "(" + Math.round(this.x) + "," + Math.round(this.y) + ") r:" + Math.round(this.radius) + " " + this.color;
}
Sprite.prototype.moveRandomly = function(speed) {
this.x += 2 * speed * Math.random() - speed;
this.y += 2 * speed * Math.random() - speed;
}
Sprite.prototype.expandRandomly = function(speed) {
this.radius += 2 * speed * Math.random() - speed;
this.radius = Math.max(3, Math.min(this.radius, 9));
}
Sprite.prototype.colorRandomly = function(speed) {
this.color.r += Math.round(2 * speed * Math.random() - speed);
this.color.g += Math.round(2 * speed * Math.random() - speed);
this.color.b +=...