1.前端一个div本身透明长宽固定且比子集大(成为画布),子集是具体内容如下图:
2.直接上代码
var getPixelRatio = function (context) { // 获取设备的PixelRatio
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 0.5;
return (window.devicePixelRatio || 0.5) / backingStore;
};
//生成的图片名称
var shareContent = document.getElementById("mapLegendViewPanle");
var width = shareContent.offsetWidth;
var height = shareContent.offsetHeight;
var canvas = document.createElement("canvas");
var context = canvas.getContext('2d');
var scale = getPixelRatio(context); //将canvas的容器扩大PixelRatio倍,再将画布缩放,将图像放大PixelRatio倍。
canvas.width = width * scale;
canvas.height = height * scale;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
canvas.style.background = 'transparent';
context.scale(scale, scale);
var opts = {
scale: scale,
canvas: canvas,
width: width,
height: height,
dpi: window.devicePixelRatio
};
html2canvas(shareContent, opts).then(function (canvasa) {
context.imageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
var source = canvasa.toDataURL('image/png', 1.0);
});
结果:画布不是透明的,但是我需要画布是透明的。
3.后来经过各方查找,终于找到解决方案。直接上代码:
在opts里加个参数backgroundColor,如果想把背景换成别的就把这个设置成自己想要的颜色就行了。
var opts = {
backgroundColor: null,//设置图片背景为透明
scale: scale,
canvas: canvas,
width: width,
height: height,
dpi: window.devicePixelRatio
};
结果:仔细对比下图跟上面图的背景是有区别的