Skip to content

Instantly share code, notes, and snippets.

@mrkmg
Last active December 20, 2015 01:49
Show Gist options
  • Save mrkmg/6051746 to your computer and use it in GitHub Desktop.
Save mrkmg/6051746 to your computer and use it in GitHub Desktop.
Creating Life - A study into HTML5 Canvas, Webworkers, and Life Simulation - Code Examples
//** Webworker.js
// Assuming we have an array of arrays, each containing an RGB value.
var colormap = [[255,255,0],[24,50,25],...,[45,64,25],[0,255,0]];
// First create a variable of a transferrable datatype
var bytes= new Uint8Array(pond.total*4);
// Loop through the array and set the colors
for(var i=0;i<colormap.length;i++){
bytes[i*4]=colormap[i][0];
bytes[i*4+1]=colormap[i][1];
bytes[i*4+2]=colormap[i][2];
bytes[i*4+3]=255; //Assume full opacity. 255 for opaque, 0 for transparent
}
// Send this byte array back to the UI Thread
self.postMessage({type:'colormap',value:bytes});
//** UIThread.js
//Assuming the webworker has been intialized and started already
var worker = new Worker('js/wk_pond.js');
...
// code to set options and start worker
...
// code to setup the canvas for exact scaling with no "smoothing" (to give you a sharper, less blurry image) and a
// temporary canvas;
var height = 100;
var width = 150;
var scale = 5;
var pond = $('canvas#pond');
pond.attr('height',height*scale);
pond.attr('width',width*scale);
var pondCtx = pond.getContext("2d");
pondCtx.imageSmoothingEnabled = false;
pondCtx.webkitImageSmoothingEnabled = false;
pondCtx.mozImageSmoothingEnabled = false;
var tmpCanvas = $('<canvas>').attr('width',width).attr('height',height)[0];
var tmpCanvasCtx = tmpCanvas.getContext("2d");
// This adds a listener for messages from the webworker thread. On the message type of color map it creates a new ImageData
// with the unscaled width and heigh, copies to data to the ImageData, then uses the built in scaling feature to scale the
// image to the full desired size.
worker.addEventListener('message',function(e){
var value = e.data.value;
switch(e.data.type){
...
case 'colormap':
var data = pondCtx.createImageData(width,height);
for(var i=0;i<value.length;i++) data.data[i] = value[i];
tmpCanvasCtx.putImageData(data,0,0);
pondCtx.drawImage(tmpCanvas,0,0,width*scale,height*scale);
break;
...
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment