Skip to content

Instantly share code, notes, and snippets.

@eskimoblood
Created August 16, 2011 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eskimoblood/1149440 to your computer and use it in GitHub Desktop.
Save eskimoblood/1149440 to your computer and use it in GitHub Desktop.
Converting basic processing sketch by Daniel Shiffman to work with the plask JavaScript framework
/**
* Additive Wave
* by Daniel Shiffman.
*
* Create a more complex wave by adding two waves together.
*/
var plask = require('plask');
var xspacing = 8; // How far apart should each horizontal location be spaced
var w; // Width of entire wave
var maxwaves = 4; // total # of waves to add together
var theta = 0.0;
var amplitude = []; // Height of wave
var dx = []; // Value for incrementing X, to be calculated as a function of period and xspacing
var yvalues = [];
plask.simpleWindow({
width: 500,
height: 400,
init:function() {
var canvas = this.canvas, paint = this.paint;
this.framerate(30);
paint.setStyle(paint.kFillStyle);
paint.setFlags(paint.kAntiAliasFlag);
paint.setColor(80, 0, 0, 50);
w = 400 + 16;
yvalues = new Array(w / xspacing);
for (var i = 0; i < maxwaves; i++) {
amplitude[i] = random(10, 30);
period = random(100, 300); // How many pixels before the wave repeats
dx[i] = (plask.k2PI / period) * xspacing;
}
},
draw:function() {
var canvas = this.canvas, paint = this.paint;
canvas.drawColor(255, 255, 255, 255);
this.calcWave();
for (var i = 0; i < yvalues.length; i++) {
canvas.drawCircle(paint, i * xspacing, 200 + yvalues[i], 16);
}
},
calcWave: function() {
theta += 0.02;
// Set all height values to zero
for (var i = 0; i < yvalues.length; i++) {
yvalues[i] = 0;
}
// Accumulate wave height values
for (var j = 0; j < maxwaves; j++) {
var x = theta;
for (var i = 0; i < yvalues.length; i++) {
// Every other wave is cosine instead of sine
yvalues[i] += Math[j % 2 ? 'sin' : 'cos'](x) * amplitude[j];
x += dx[j];
}
}
}
});
function random(min, max) {
return min + Math.random() * (max - min)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment