html2canvas JS截圖插件

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

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

html2canvas 能夠將html頁面保存爲圖片,至關於進行截圖,能夠應用於一些活動H5的海報生成。github

 

 

能夠下載好文件經過script標籤引入,或者經過npm安裝npm

npm install html2canvas

 

用法:canvas

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

//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 改成truepromise

var opts = {useCORS: true}; html2canvas(element, opts);
相關文章
相關標籤/搜索