Processing Oscilating circles
2015-08-12 [EverydaySketch]
by schrodingers
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.13/processing.min.js"></script>
<canvas></canvas>
CSS
</style> <script type="text/javascript"> window.addEventListener('load', function() {
var scripts=document.body.getElementsByTagName('script');
var canvases=document.body.getElementsByTagName('canvas');
new Processing(canvases[0], scripts[0].text);
}
, false);
// Here prevent javascript in body from throwing error </script> <style>
JavaScript
/*
title: exercise week 3_02 sin() processing function
date: 2015-08-12
* three arrays that store the y-position, speed and phase of oscillating circles.
*/
color[] spring = {
#ff6699, #ff9900, #ffcc00, #9adb1b, #00cc66, #00cccc, #00ccff, #6633cc, #ff66cc
};
color[] flat = {
#2ecc71, #e74c3c, #3498db, #9b59b6, #f1c40f, #e67e22, #be643c, #ecf0f1, #1abc9c, #2c3e50, #f5f5f5, #bdc3c7, #7f8c8d, #95a5a6, #e0e0e0, #34495e
};
int num;
float d;
float[] y; // y-position of each circle (fixed)
float[] x;
float[] speed; // speed of each circle
float[] phase; // start offset of each circle
boolean[] stopped; // state of each circle
float hue = 30;
float satur = 90;
float lightness = 90;
void setup() {
size(600, 600);
num = 10;
// allocate space for each array
y = new float[num];
x = new float[num];
speed = new float[num];
phase = new float[num];
stopped = new boolean[num];
d = 30;
// calculate the gap in y based on the number of circles
float gap = height / (num + 1);
for (int i=0; i<num; i++) {
y[i] = gap * (i + 1); // y is constant for each so can be calculated once
speed[i] = random(3);
phase[i] = random(TWO_PI);
stopped[i] = false;
}
}
void draw() {
colorMode(RGB, 255, 255, 255, 10);
fill(250, 250, 250, 4);
rect(0, 0, width, height);
noStroke();
colorMode(HSB, 360, 100, 100);
for (int i=0; i<num; i++) {
// calculate the x-position of each ball based on the speed, phase and current frame
if (!stopped[i]) {
x[i] = width/2 + sin(radians(frameCount*speed[i] ) + phase[i])* width/4;
}
fill(hue*i, satur, lightness);
ellipse(x[i], y[i], d, d);
}
}
void mouseClicked() {
for (int i=0; i < num; i++) {
if (dist(mouseX, mouseY, x[i], y[i]) < d/2) {
stopped[i] = !stopped[i];
if (stopped[i]) {
speed[i] = 0;
} else {
speed[i] = random(2);
phase[i] = random(TWO_PI);
}
}
}
}