So I recently needed to create a image from a part of a webpage (html) after a short googling I found a nice library, html2canvas, that can render a part of the dom as a canvas element, complete with all css properties. So that's a good start but I needed some way of making the image downloadable too. Turns out the canvas element has a function called toDataURL that returns the rendered content of the canvas as a data-url. The url can then be used with a <a> tag to create a download link. So the complete example looks something like this.
This works fine in Chrome & Firefox whoever not in Internet Explorer, in IE a small hack is needed. Due to 'security' reasons IE doesn't allow data urls in <a> tags so instead you need to decode the data from the canvas and create a blob object that can be passed to the window.navigator.msSaveOrOpenBlob function.
varisIe=function(){vartrident=!!navigator.userAgent.match(/Trident\/7.0/);varnet=!!navigator.userAgent.match(/.NET4.0E/);varie11=trident&&net;variEold=(navigator.userAgent.match(/MSIE/i)?true:false);returnie11||iEold;};varworkInHorribleIE=function(canvas,filename){varimage=canvas.toDataURL();image=image.substring(22);// remove data stuffvarbyteString=atob(image);varbuffer=newArrayBuffer(byteString.length);varintArray=newUint8Array(buffer);for(vari=0;i<byteString.length;i++){intArray[i]=byteString.charCodeAt(i);}varblob=newBlob([buffer],{type:"image/png"});window.navigator.msSaveOrOpenBlob(blob,filename+".png");};html2canvas($("#cctree"),{onrendered:function(canvas){var$a;if(isIe()){$a=$("<a>download</a>").on("click",function(){workInHorribleIE(canvas,"file");});}else{$a=$("<a download=\"file.png\" href=\""+canvas.toDataURL()+"\">download</a>");}$("table",$cntnt).parent().append($a);}});
Guess there's better ways to detect if IE is present and most of the data-url to blob stuff should be replaced with a toBlob call once it's supported.