有没有办法以编程方式将DIV中的内容导出到图像?

时间:2011-12-20 01:40:27

标签: javascript asp.net

  

可能重复:
  Take a screenshot of a webpage with javascript?

我希望以编程方式将DIV中的内容导出到图像中?我能怎么做?哪些代码可以做到这一点,服务器代码或客户端代码? 谢谢!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
     <div id="a">
       Content to export to image
     </div>

     <div id="b">
       Normal text
     </div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

您可以使用SVG

执行此操作

示例:

<?xml version="1.0" standalone="yes"?>
<svg xmlns = "http://www.w3.org/2000/svg">
  <foreignobject x="120" y="120" width="180" height="180">
    <body xmlns="http://www.w3.org/1999/xhtml">
      <div>
        Something
      </div>
    </body>
  </foreignobject>
</svg>

或者你拥有的东西之后:

<canvas id="canvas" width="200" height="200"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = "data:image/svg+xml," +
           "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
             "<foreignObject width='100%' height='100%'>" +
               document.getElementById('a').innerHTML +
             "</foreignObject>" +
           "</svg>";
var img = new Image();
img.src = data;
img.onload = function() { ctx.drawImage(img, 0, 0); }

希望这会对你有所帮助。取自Mozilla Docs