好久前寫了關於把html轉成圖片的一個例子,最近有出了新的問題。利用html2canvas.js文件把html轉成base64位的圖片是沒什麼問題的,但也不是絕對的,好比這時候不能遇見svg這個鬼,html2canvas遇見svg就很差用了,svg的元素會不能出如今生成的圖片中。這時候我看到了html2canvas.svg.min.js這個文件,奈何我沒找到正確的使用方式。因此選擇了canvg.js 這個goole發明的方法,原理是把svg裝成canvas,再利用canvas的toDataURL,轉成base64位的圖片形式。好了,看例子吧。javascript
canva.js 須要依賴於rgbcolor.js。這個應該都比較容易下載到。html
附上下載地址:https://github.com/canvg/canvgjava
看例子啦,很簡單的(引用git中的一個例子):git
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 2 <html> 3 <head> 4 <title>canvg.js callback test</title> 5 <!--[if IE]> 6 <script type="text/javascript" src="flashcanvas.js"></script> 7 <![endif]--> 8 <script type="text/javascript" src="../rgbcolor.js"></script> 9 <script type="text/javascript" src="../canvg.js"></script> 10 <script type="text/javascript"> 11 var context; 12 var redraw = false; 13 function resize() { 14 var c = document.getElementById('container'); 15 c.style.width = (window.innerWidth || document.body.clientWidth)+'px'; 16 c.style.height = (window.innerHeight || document.body.clientHeight)+'px'; 17 redraw = true; 18 } 19 function bodyonload() { 20 if (typeof(FlashCanvas) != 'undefined') context = document.getElementById('canvas').getContext; 21 var svg = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" preserveAspectRatio="none" viewBox="0 0 100 100" style="width:100%; height:100%;">' 22 +'<linearGradient id="background_gradient_black" x1="0%" y1="10" x2="0%" y2="90" gradientUnits="userSpaceOnUse">' 23 +'<stop offset="0%" stop-color="#000" stop-opacity="1" />' 24 +'<stop offset="35%" stop-color="#200" stop-opacity="1" />' 25 +'<stop offset="65%" stop-color="#600" stop-opacity="1" />' 26 +'<stop offset="100%" stop-color="#ff0" stop-opacity="1" />' 27 +'</linearGradient>' 28 +'<rect x="0" y="0" width="100" height="100" fill="url(#background_gradient_black)" />' 29 +'</svg>'; 30 resize(); 31 canvg('canvas', svg, { 32 ignoreMouse: true, 33 ignoreAnimation: true, 34 renderCallback: function() { alert('done rendering!'); }, 35 forceRedraw: function() { var update = redraw; redraw = false; return update; } 36 }); 37 } 38 window.onresize = resize; 39 </script> 40 </head> 41 <body onload="bodyonload();"> 42 <div id="container"><canvas id="canvas"></canvas></div> 43 </body> 44 </html>