Brownian Motion in HTML5 Canvas
Ya know, cause I couldn’t find it anywhere (Lovingly stolen from Processing documentation). View the example.
I’m hoping to convert Craig Reynolds’ Boids to JavaScript/Canvas at some point in the future, too.
window.addEventListener('load', init, false);
function init(){
var canvas = document.getElementById("canvas");
if (canvas.getContext('2d')){
main(canvas);
} else {
console.log("Canvas tag is not supported");
}
}
function main(canvas){
var canvas = canvas;
var ctx = canvas.getContext("2d");
const CANVAS_WIDTH = canvas.width;
const CANVAS_HEIGHT = canvas.height;
var num = 10;
var range = 200;
var ax = [];
var ay = [];
for(var i = 0; i < num; i++) {
ax[i] = CANVAS_WIDTH/2;
ay[i] = CANVAS_HEIGHT/2;
}
setInterval(draw, 30);
function draw(){
// Shift all elements 1 place to the left
for(var i = 1; i < num; i++) {
ax[i-1] = ax[i];
ay[i-1] = ay[i];
}
// Put a new value at the end of the array
var r2x = range*2;
ax[num-1] += (Math.random()*r2x)-range;
ay[num-1] += (Math.random()*r2x)-range;
// Constrain all povars to the screen
ax[num-1] = constrain(ax[num-1], 0, CANVAS_WIDTH);
ay[num-1] = constrain(ay[num-1], 0, CANVAS_HEIGHT);
// Draw a line connecting the povars
for(var i = 1; i < num; i++) {
var alpha = i/num;
ctx.globalAlpha = i/num;
ctx.moveTo(ax[i-1], ay[i-1]);
ctx.lineTo(ax[i], ay[i]);
ctx.stroke();
}
}
function constrain(val, min, max){
if(val > max){
val = max;
}else if(val < min){
val = min;
}
return val;
}
}
Leave a Reply
About Me
I'm a designer, developer, and teacher based in Harrisburg, Pa. I run Hauck Interactive, Inc.
Categories
Archives
- January 2012
- December 2011
- October 2011
- August 2011
- July 2011
- June 2011
- May 2011
- March 2011
- February 2011
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
- April 2007
- March 2007
- February 2007
- January 2007
- December 2006
- November 2006
- October 2006
- September 2006
- August 2006
- July 2006
- June 2006
- May 2006
- April 2006
- March 2006
- February 2006
- January 2006
- December 2005
- November 2005
- October 2005
- September 2005

