
Untitled
By: a guest on
Jul 20th, 2012 | syntax:
None | size: 1.24 KB | hits: 10 | expires: Never
$.fn.canvasToImage =
function(backgroundColor) {
var canvas = $(this).find('canvas');
if (!backgroundColor) backgroundColor = '#fff';
//cache height and width
var w = canvas[0].width;
var h = canvas[0].height;
$('body').append('<canvas id="tempcanvas" />');
$("#tempcanvas").attr('width',w).attr('height',h);
var newCanvas = $("#tempcanvas")[0];
var newContext = newCanvas.getContext("2d");
newContext.clearRect(0,0,w,h);
var allData = newContext.getImageData(0, 0, w, h);
$(canvas).each(function(){
var context = $(this)[0].getContext("2d");
var imageData = context.getImageData(0, 0, w, h);
var pixels = 4 * w * h;
while (pixels--) {
allData.data[pixels] = allData.data[pixels] + imageData.data[pixels];
}
});
newContext.putImageData(allData, 0,0);
newContext.globalCompositeOperation = "destination-over";
newContext.fillStyle = backgroundColor;
newContext.fillRect(0,0,w,h);
//get the image data from the canvas as a Base64 encoded data url string
var imageData = newCanvas.toDataURL("image/png");
$('#tmepcanvas').remove();
return imageData;
};