js把某個div或其他元素用圖片的形式導出或下載
阿新 • • 發佈:2018-04-26
doc ros 頁面 save 兩個 left cal create 導出
很多時候需要用到把頁面上的某個塊元素用圖片的形式導出來,例如導出一些表格構成的單據
思路:把指定的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: 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: width,
height: height
});
//顯示圖片-end
//導出圖片
window.Canvas2Image.saveAsPNG(canvas, width * scale, height * scale);
});
}
};
html2Img.init();
</script>
js把某個div或其他元素用圖片的形式導出或下載