4

I have image size 32*32 and have array of each pixel color.This color is the combination of red green blue .i want to draw image using this array in javascript. how to draw image using this information?

user894554
  • 258
  • 5
  • 18
  • There are good ways to do this now. See http://stackoverflow.com/questions/13416800/how-to-generate-an-image-from-imagedata-in-javascript. – Don McCurdy Mar 30 '16 at 03:05

2 Answers2

4

The short answer is that you shouldn't do this in JavaScript, as it should be a server operation for a variety of reasons. However, you'll need to provide more details about what you're trying to do. There are a number of routes to take:

  • Use blocks of DIVs. This is very slow and probably the worst way of doing it, but it is likely the easiest to understand.
  • Use HTML Canvas (or a canvas-like alternative, like excanvas). Probably the next simplest, though I think it is the least useful for anything beyond a toy.
  • Draw something out in SVG (or SVG-like through something like RaphaelJS). This will look the best as a general rule, although 32x32 blocks seems pretty small.
  • Interface with a renderer built in some plug-in like Flash or Silverlight.

Let's take a breakdown of the canvas method (using native canvas commands for browsers like Chrome):

var drawingCanvas = document.getElementById('myDrawing');
if(!drawingCanvas.getContext) 
{
    return;
}
var context = drawingCanvas.getContext('2d');
var pixSize = 1;
for (var i=0; i < rows.length; i++)
{
    var col = rows[i];
    for (var j=0; j < col.length; j++)
    {
        context.fillStyle = col[j]; // assumes the data is in #hex format already.
        context.fillRect(j*pixSize,i*pixSize,pixSize,pixSize);
    }
}
John Green
  • 13,241
  • 3
  • 29
  • 51
-1

This assumes that your pixel colors are all in hexadecimal format. If they aren't you'll need to convert them somehow:

var imgData = [ /* your array of pixel colors */ ],
    img = document.createElement('div'),
    i = 0, l = imgData.length,
    pixel;
img.style.cssText = 'overflow:hidden; width:32px; height:32px';
while (i < l) {
    pixel = document.createElement('div');
    pixel.style.cssText =
        'float:left; width:1px; height:1px; background-color:#' + imgData[i];
    img.appendChild(pixel);
    i += 1;
}
document.body.appendChild(img);
sdleihssirhc
  • 42,000
  • 6
  • 53
  • 67