svg转化成canvas以便生成base64位的图片

很久前写了关于把html转成图片的一个例子,最近有出了新的问题。利用html2canvas.js文件把html转成base64位的图片是没什么问题的,但也不是绝对的,比如这时候不能碰见svg这个鬼,html2canvas碰见svg就不好用了,svg的元素会不能出现在生成的图片中。这时候我看到了html2canvas.svg.min.js这个文件,奈何我没找到正确的使用方式。所以选择了canvg.js 这个goole发明的方法,原理是把svg装成canvas,再利用canvas的toDataURL,转成base64位的图片形式。好了,看例子吧。

 

canva.js 需要依赖于rgbcolor.js。这个应该都比较容易下载到。

附上下载地址:https://github.com/canvg/canvg

看例子啦,很简单的(引用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>

 

posted @ 2016-12-05 14:37  xiaoss  阅读(11592)  评论(0编辑  收藏  举报