I would like to know a way to generate a single pixel in JavaScript converting it to base64. The ideal function would be:
function createPixel(hexColor, opacity){
//...Calculate
return base64DataURL;
}
I am not very familiar with image processing. Any format is fine (png, gif etc). I would like to use this to overlay background images, (yes I could use rgba css3 but I am trying to place it with a background-image only on one element so i am not overlaying an element on top of another to achieve the effect).
Thanks in advance.
Edit: I would like not to use canvas, I am sure you can use canvas to get the base64 dataURL but I am sure it is not as fast as a string manipulation. Also I am not worried about converting an image into base64 but more interested in creating the image.
Here's a fully cross-browser-compatible implementation using <canvas>
(demo @ jsfiddle).
var canvas = document.createElement('canvas');
// http://code.google.com/p/explorercanvas/wiki/Instructions#Dynamically_created_elements
if (!canvas.getContext) G_vmlCanvasManager.initElement(canvas);
var ctx = canvas.getContext('2d');
canvas.width = 1;
canvas.height = 1;
// for simplicity, assume the input is in rgba format
function createPixel(r, g, b, a) {
ctx.fillStyle = 'rgba(' + [r,g,b,a].join() + ')';
ctx.fillRect(0,0,1,1);
// 'data:image/png;base64,'.length => 22
return canvas.toDataURL('image/png','').substring(22);
}
I was curious to see how this stacks up against icktoofay's answer, performance-wise. Note, this will have to use excanvas for IE <9, which means that performance will almost certainly be worse there (but what's new).
Check out the jsperf: http://jsperf.com/base64image