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 i开发者_JAVA百科mage using this information?
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);
}
}
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);
精彩评论