Is it possible to generate an Image from an Array with Hex Codes and if yes how?
This Array: ["#ffffff", "#ff0000", "#ffff00"]
Would output an Image where the first pixel has the color: "#ffffff", the second: "#ff0000", the third: "#ffff00" and so on...
My Method was to create a ton of div elements that all had diffrent background-colors, but if you have a huge array thats really slow...
My method looks something like this:
var index;
for (index = 0; index < array.length; index++) {
var indexx;
$("container").append("<div style='background-color: " + array[length] + "; position: absolute; top: 0; left: " + index + ";'></div>");
}
What i need is something like this: http://jsfiddle.net/Evilzebra/9xnn8tw5/ But with colors aswell...
Edit:
//create some random data for example
var data = [];
for(var i = 0, l = 1000000; i < l; i++){
data.push(Math.round(Math.random()*255));
}
var image = document.getElementById('i');
//display image only after it's loaded
image.onload = function(){this.style.display='block'}.bind(image);
//and finally set the .src
image.src = dataToBase64(data, 1000, 1000);
function dataToBase64(colors, width, height){
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
color;
//setup canvas
canvas.width = width,
canvas.height = height;
//grab data
var data = ctx.getImageData(0, 0, width, height),
_data = data.data; //simple speed optimization
//place data
for(var i = 0, l = _data.length; i < l; i+3){
_data[i] = colors[i],
_data[i+1] = color[i+1],
_data[i+2] = color[i+2],
_data[i+3] = 255;
}
ctx.putImageData(data, 0, 0);
//return base64 string
return canvas.toDataURL();
}
Should give the pixels random colors... but it doesnt works...
See the fiddle above and paste the code there...
canvasis for. You can target each pixel individually. PS the size of the array probably wasn't causing the slowdown; the number of elements you were probably trying to place on the page was. I've used canvas to create images from a large array of pixel colours and it's very fast.