抓取html 生成图片

Posted on 2018-06-12 10:58  陈小鑫  阅读(477)  评论(0编辑  收藏  举报
  <!DOCTYPE html>
  <html>
  <head>
  <script type="text/javascript" src="https://www.tianjihr.com/VipTemplates/1563089/1/js/jquery-1.8.2.min.js"></script>
  <script type="text/javascript" src="http://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
  <style>
  * {
  margin: 0;
  }
   
   
  .test {
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  background-color: #87CEEB;
  display: inline-block;
  vertical-align: top;
  }
   
   
  canvas {
  margin-right: 5px;
  }
   
   
  .down {
  float: left;
  margin: 40px 10px;
  }
  .down2 {
  float: left;
  margin: 40px 30px;
  }
  .test.active{ display:none;}
  </style>
  </head>
  <body>
  <div class="test" id="www">测试<span>11212145</span></div>
   
  <img class="sc" src="" />
  <script>
  //直接选择要截图的dom,就能截图,但是因为canvas的原因,生成的图片模糊
  //html2canvas(document.querySelector('div')).then(function(canvas) {
  // document.body.appendChild(canvas);
  //});
  //创建一个新的canvas
  var canvas2 = document.createElement("canvas");
  let
  _canvas = document.querySelector('div');
  var w = parseInt(window.getComputedStyle(_canvas).width);
  var h = parseInt(window.getComputedStyle(_canvas).height);
  //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
  canvas2.width = w * 2;
  canvas2.height = h * 2;
  canvas2.style.width = w + "px";
  canvas2.style.height = h + "px";
  //可以按照自己的需求,对context的参数修改,translate指的是偏移量
  // var context = canvas.getContext("2d");
  // context.translate(0,0);
  var context = canvas2.getContext("2d");
  context.scale(2, 2);
   
  html2canvas(document.querySelector('div'), { canvas: canvas2 }).then(function(canvas) {
  $('.sc').attr('src',canvas.toDataURL())
  if($('.sc').attr('src')!=''){
  $('.test').addClass('active')
  }
   
  });
  </script>
   
  </body>
  </html>