html2canvas生成长图
2017-11-22 16:00阅读:
近期项目中用到了生成长图的功能,调研了html2canvas和dom-to-image这两个插件。因为是在微信端的项目,用dom-to-image的toSvg()方法(用此方法,是因为可以保证清晰度),但是长按图片无法保存到本地相册。最后选择html2canvas。
一、应用场景
![html2canvas生成长图 html2canvas生成长图]()
如上 两个div,点击按钮,需要把div2的dom内容生成一张图片。
二、实现方法
(1)去官网http://html2canvas.hertzen.com/下载html2canvas.js,然后放置在项目中,并在相应的页面引入。
注:前提引入jquery或者zepto
(2)书写js
var
dom=$('#div2');
//你要转变的dom
html2canvas(dom[0],
{
onrendered: function
(canvas) {
var url = canvas.toDataURL();
//生成长图的路径
$('#grow-img').attr('src',url);
}
});
(3)问题1:如果dom内容超过一屏,只能生成当前屏幕的内容,并且生成图片清晰度模糊。解决办法如
下:
修改html2canvas.js源码,第一处源码943行,增加options.width和options.height,修改如下:
width = options.width !=
null ? options.width :
node.ownerDocument.defaultView.innerWidth;
height =
options.height != null ?
options.height :
node.ownerDocument.defaultView.innerHeight;
return
renderDocument(node.ownerDocument,
options, width, height,
index).then(function(canvas) {
if
(typeof(options.onrendered) ===
'function') {
log('options.onrendered is deprecated,
html2canvas returns a Promise containing the canvas');
options.onrendered(canvas);
}
return canvas;
});
第二处999行,修改如下,增加options.scale和options.canvas:
if (options.type ===
'view') {
canvas =
crop(renderer.canvas,
{width:
renderer.canvas.width,
height:
renderer.canvas.height,
top: 0, left:
0, x: 0, y:
0});
} else if (node ===
clonedWindow.document.body
|| node ===
clonedWindow.document.documentElement)
{
canvas =
renderer.canvas;
}else if(options.scale &&
options.canvas !=null){
log('放大canvas',options.canvas);
var scale = options.scale ||
1;
canvas =
crop(renderer.canvas,
{width: bounds.width *
scale,
height:bounds.height *
scale, top:
bounds.top *scale,
left: bounds.left
*scale, x: 0,
y: 0});
}
最后,修改js代码如下,需要引入canvas2image.js:
var
dom=$('#div2');
//你要转变的dom
var width =
dom.width();
var height =
dom.height();
var type = 'png';
var scaleBy = 3;
//缩放比例
var testcanvas
=
document.createElement_x_x_x_x_x_x('canvas');
testcanvas.width = width *
scaleBy;
testcanvas.height = height *
scaleBy;
testcanvas.style.width =
width * scaleBy +
'px';
testcanvas.style.height =
height * scaleBy +
'px';
var context =
testcanvas.getContext('2d');
context.scale(scaleBy,
scaleBy);
html2canvas(dom[0], {
canvas:testcanvas,
scale:scaleBy,
width:width, //dom
原始宽度
height:height,//dom
原始高度
onrendered: function (canvas)
{
var img=
Canvas2Image.convertToImage(canvas,width*
scaleBy,height*
scaleBy,type);//这是放大了很3倍的图片,利用canvas2image.js生成img对象
$('#grow-img').attr('src',$(img).attr('src'));
}
});
问题2:上述操作都做完之后,很奇怪,生成了一张透明的图片,很纳闷,后来单独写了一个简单的页面,用同样的方法可以生成图片,怀疑是dom的问题,然后把div1和div2位置调换,让div2紧挨body,竟然可以生成图片了。
问题3:通过上面这些操作,可以生成图片了,但是跨域的图片生成长图后显示不出来,可以通过nginx域名转发,把http请求的图片的域名转发成项目域名,即可显示跨域的图片