js把某个div或其他元素用图片的形式导出或下载

很多时候需要用到把页面上的某个块元素用图片的形式导出来,例如导出一些表格构成的单据
思路:把指定的html内容转换成canvas,然后再转换成图片
这里推荐使用这两个库


<script src="https://superal.github.io/canvas2image/canvas2image.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

<script>
//使用例子
var html2Img = {
  init: function() {
    this.initDom();
    this.initEvent();
  },
  initDom: function() {
    this.$el = {};
    this.$el.$startBtn = $('#clickBtn');//触发元素
    this.$el.$htmlSource = $('#youhtml');//要导出的html
    this.$el.$pngContent = $('#imgshow');//转换后的图片展示
  },
  initEvent: function() {
    var me = this;
    this.$el.$startBtn.on('click', function() {
      me.initSavePng(2);
    });
  },
  initSavePng: function(N) {
    var me = this;
    var sourceContent = me.$el.$htmlSource;
    var width = sourceContent.width();
    var height = sourceContent.height();
    var offsetTop = sourceContent.offset().top;
    var offsetLeft = sourceContent.offset().left;
    var canvas = document.createElement("canvas");
    var canvas2D = canvas.getContext("2d");
    // 不能小于1,否则图片不完整
    var scale = N;
    canvas.width = (width + offsetLeft) * scale;
    canvas.height = (height + offsetTop) * scale;
    canvas2D.scale(scale, scale);
    canvas2D.font = "Microsoft YaHei";
    var options = {
      //检测每张图片都已经加载完成
      tainttest: true,
      canvas: canvas,
      scale: scale,
      //dom 放大的宽度,放大倍数和清晰度在一定范围内成正相关
       width + offsetLeft,
      // 开启日志,可以方便调试
      logging: true,
      //dom 放大的宽度,放大倍数和清晰度在一定范围内成正相关
      height: height + offsetTop
    };
    html2canvas(sourceContent, options).then(function(canvas) {
      //显示图片-start
      var img = window.Canvas2Image.convertToPNG(canvas, width * scale, height * scale);
      me.$el.$pngContent.append(img);
      // 将图片恢复到原始大小
      me.$el.$pngContent.find('img').css({
         width,
        height: height
      });
      //显示图片-end
      //导出图片
      window.Canvas2Image.saveAsPNG(canvas, width * scale, height * scale);
    });
  }
};
html2Img.init();
</script>
原文地址:https://www.cnblogs.com/chriiess/p/8952028.html