<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
<title>DIV元素截图转图片</title>
</head>
<body>
<div id="a0">
<div id="strategyContentView" style="background-color: black;width: 211px; height: 112px; letter-spacing: 0px; text-align: center; font-family: 黑体; text-align-last: center; font-weight: bold; color: red;margin-top:0px;">
<p id="pMain">
<span style="display: block;">前方道路</span>
<span style="display: block;">发生交通事故</span>
<span style="display: block;">请注意避让</span>
</p>
</div>
</div>
<script type="text/javascript">
//1.将div转成svg
var divContent = document.getElementById("a0").innerHTML;
var data = "data:image/svg+xml," +
"<svg xmlns='http://www.w3.org/2000/svg' width='211' height='112' style='display:block;'>" +
"<foreignObject width='100%' height='100%'>" +
"<div xmlns='http://www.w3.org/1999/xhtml'>" +
divContent +
"</div>" +
"</foreignObject>" +
"</svg>";
var img = new Image();
img.src = data;
//document.getElementsByTagName('body')[0].appendChild(img);
//2.svg转成canvas
var canvas = document.createElement('canvas'); //准备空画布
canvas.width = img.width;
canvas.height = img.height;
document.body.appendChild(canvas);
var context = canvas.getContext('2d'); //取得画布的2d绘图上下文
context.drawImage(img,0,0);
//3. 图片导出为 png 格式
var type = 'png';
var imgData = canvas.toDataURL(type);
console.log(imgData);
</script>
</body>
</html>