前言
将div转base64图片
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>div-svg-base64</title>
<script type="text/javascript" src="/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/js/html2canvas.min.js"></script>
<style>
</style>
</head>
<body>
<div id="divId">
<table border="1">
<thead>
<tr><td>姓名</td><td>年龄</td><td>地址</td></tr>
</thead>
<tbody>
<tr><td>王多余</td><td>16</td><td>深圳市南山区</td></tr>
<tr><td>神疼</td><td>26</td><td>深圳市保安区</td></tr>
</tbody>
</table>
<table border="1">
<thead>
<tr><td>姓名</td><td>年龄</td><td>地址</td></tr>
</thead>
<tbody>
<tr><td>王多余</td><td>16</td><td>深圳市南山区</td></tr>
<tr><td>神疼</td><td>26</td><td>深圳市保安区</td></tr>
</tbody>
</table>
</div>
<input type="button" value="click" onclick="divToImg()" />
<img src="" id="img" />
</body>
<script>
function divToImg() {
var divContent = document.getElementById("divId").innerHTML;
var data = "data:image/svg+xml," +
"<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
"<foreignObject width='100%' height='100%'>" +
"<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:16px;font-family:Helvetica'>" +
divContent +
"</div>" +
"</foreignObject>" +
"</svg>";
var img = new Image();
img.src = data;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
img.crossOrigin = "anonymous";
img.onload = function() {
ctx.drawImage(img, 0, 0);
var canvasbase = canvas.toDataURL();
document.getElementById("img").setAttribute('src', canvasbase)
}
}
</script>
</html>
html2canvas.min.js 下载地址: https://blog-static.cnblogs.com/files/lyt520/html2canvas.min.js
jquery下载地址: https://code.jquery.com/jquery-3.2.1.min.js
运行结果示例