Personal and Professional Blog of Rich Hauck

Brownian Motion in HTML5 Canvas

January 20, 2012

Brownian Motion

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;
	}
}
Categories: canvas, HTML5

Leave a Reply

About Me

Rich HauckI'm a designer, developer, and teacher based in Harrisburg, Pa. I run Hauck Interactive, Inc.




Archives