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,
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);
原文地址:https://www.cnblogs.com/haqiao/p/10364006.html