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

时间:2024-04-04 12:33:51

很久前写了关于把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中的一个例子):

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>canvg.js callback test</title>
<!--[if IE]>
<script type="text/javascript" src="flashcanvas.js"></script>
<![endif]-->
<script type="text/javascript" src="../rgbcolor.js"></script>
<script type="text/javascript" src="../canvg.js"></script>
<script type="text/javascript">
var context;
var redraw = false;
function resize() {
var c = document.getElementById('container');
c.style.width = (window.innerWidth || document.body.clientWidth)+'px';
c.style.height = (window.innerHeight || document.body.clientHeight)+'px';
redraw = true;
}
function bodyonload() {
if (typeof(FlashCanvas) != 'undefined') context = document.getElementById('canvas').getContext;
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%;">'
+'<linearGradient id="background_gradient_black" x1="0%" y1="10" x2="0%" y2="90" gradientUnits="userSpaceOnUse">'
+'<stop offset="0%" stop-color="#000" stop-opacity="1" />'
+'<stop offset="35%" stop-color="#200" stop-opacity="1" />'
+'<stop offset="65%" stop-color="#600" stop-opacity="1" />'
+'<stop offset="100%" stop-color="#ff0" stop-opacity="1" />'
+'</linearGradient>'
+'<rect x="0" y="0" width="100" height="100" fill="url(#background_gradient_black)" />'
+'</svg>';
resize();
canvg('canvas', svg, {
ignoreMouse: true,
ignoreAnimation: true,
renderCallback: function() { alert('done rendering!'); },
forceRedraw: function() { var update = redraw; redraw = false; return update; }
});
}
window.onresize = resize;
</script>
</head>
<body onload="bodyonload();">
<div id="container"><canvas id="canvas"></canvas></div>
</body>
</html>