html2canvas JS截圖插件


github/download:https://github.com/niklasvh/html2canvas/releases

參考文章: 基於html2canvas實現網頁保存為圖片及圖片清晰度優化

html2canvas 可以將html頁面保存為圖片,相當於進行截圖,可以應用於一些活動H5的海報生成。

 

 

可以下載好文件通過script標簽引入,或者通過npm安裝

npm install html2canvas

 

用法:

基於html2canvas.js可將一個元素渲染為canvas,只需要簡單的調用html2canvas(element[, options]);即可。下列html2canvas方法會返回一個包含有<canvas>元素的promise

//targetEl 是需要截圖的元素,可以是某一個DIV,也可以是當前整個document,options是參數項,可配置寬高之類的,也可省略不傳,返回一個canvas的dom對象
html2canvas(targetEl,options).then(function(canvas) {
    document.body.appendChild(canvas);
});


//之前做一個生成海報的H5的例子代碼
var poster = document.querySelector('#wrap') //要生成海報的DIV,最外層的
var width = poster.offsetWidth;
var height = poster.offsetHeight;
var canvas = document.createElement("canvas");
var scale = 2;

canvas.width = width * scale;
canvas.height = height * scale;
canvas.getContext("2d").scale(scale, scale);

var opts = {
scale: scale,
canvas: canvas,
width: width,
height: height ,
backgroundColor:'transparent'
};

//生成頁面截圖
html2canvas(poster,opts).then(function(canvas) {
var context = canvas.getContext('2d');

var img = new Image();
img.src = canvas.toDataURL()
img.id = 'poster'

poster.appendChild(img); //生成海報插入body , 海報是透明的 ,層級最高, 蓋在容器上面

});
 

 

轉為圖片: html2canvas是返回的一個canvas,要保存為圖片的話就要轉為img,可以通過canvas.toDataURL()方法將canvas轉為base64

 

跨域設置:如果網頁有跨域的圖片會影響到截圖圖片的生成,可以將html2canvas 的 userCORS 改為true

var opts = {useCORS: true};

html2canvas(element, opts);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM