Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 20th, 2012  |  syntax: None  |  size: 1.24 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. $.fn.canvasToImage =
  2.     function(backgroundColor) {
  3.       var canvas = $(this).find('canvas');
  4.  
  5.       if (!backgroundColor) backgroundColor = '#fff';
  6.  
  7.       //cache height and width
  8.       var w = canvas[0].width;
  9.       var h = canvas[0].height;
  10.       $('body').append('<canvas id="tempcanvas" />');
  11.       $("#tempcanvas").attr('width',w).attr('height',h);
  12.       var newCanvas = $("#tempcanvas")[0];
  13.       var newContext = newCanvas.getContext("2d");
  14.       newContext.clearRect(0,0,w,h);
  15.       var allData = newContext.getImageData(0, 0, w, h);
  16.       $(canvas).each(function(){
  17.         var context = $(this)[0].getContext("2d");
  18.         var imageData = context.getImageData(0, 0, w, h);
  19.         var pixels = 4 * w * h;
  20.         while (pixels--) {
  21.           allData.data[pixels] = allData.data[pixels] + imageData.data[pixels];
  22.         }
  23.       });
  24.       newContext.putImageData(allData, 0,0);
  25.       newContext.globalCompositeOperation = "destination-over";
  26.       newContext.fillStyle = backgroundColor;
  27.       newContext.fillRect(0,0,w,h);
  28.       //get the image data from the canvas as a Base64 encoded data url string
  29.       var imageData = newCanvas.toDataURL("image/png");
  30.       $('#tmepcanvas').remove();
  31.       return imageData;
  32.     };