/* * This javascript file loads an image and show the image data to blocks * of a grid. * * Author: Avan Suinesiaputra */ // get image data using the callback function function getImageData( _uri, _height, _width, _callback ) { var img = new Image(); img.onload = function () { var canvas = document.createElement("canvas"); canvas.width = _width; canvas.height = _height; var ctx = canvas.getContext("2d"); ctx.drawImage(this,0,0); _callback(ctx.getImageData(0,0,_width,_height)); } img.src = _uri; } getImageData("profile.jpeg", 32, 32, function(_imgData) { // need to convert the image // for n*m image, it becomes 4*n*m array, where each item is [r,g,b,a] // we're going to create a gray scale image value var imgarr = Array.from(_imgData.data); var pixval = []; while( imgarr.length ) { var x = imgarr.splice(0,4); pixval.push( Math.round( x.slice(0,3) .reduce(function (a,b) { return a+b; }, 0) / 3 ) ); } var nrow = 32, ncol = 32, width = 20, height = 20; // draw the squares d3.select("svg") .selectAll(".cell") .data(pixval) .enter() .append("g") .attr("class", "cell") .attr("transform", function (d, i) { return "translate(" + ((i % ncol)*width) + "," + (Math.floor(i / ncol)*height) + ")" }) .append("rect") .attr("width", width) .attr("height", height) .attr("fill", function(d) { return "rgb(" + d + "," + d + "," + d + ")"; } ); });