js 截屏保存图片
html2canvas.js 这个js有个强大的功能,就是能将html 对应的dom生成canvas。
这样,我们就可以通过生成的canvas转化成 base64 图片,从而实现截屏功能;
核心代码如下(同时也解决了一个bug,生成的图片不高清):
//以下乘以3是将画布和画布的内容放大3被,从而使生成的图片变清晰 var canvas = document.createElement("canvas"); canvas.height = $(window).height()*3 canvas.width = $(window).width()*3 var context = canvas.getContext("2d"); //然后将画布缩放,将图像放大两倍画到画布上 context.scale(3,3);
html2canvas(document.getElementById('view'), { canvas: canvas, onrendered: function(canvas) { var _h = $(window).height()*2/3; var _w = $(window).width()*2/3; _src = canvas.toDataURL('image/png'); var img = new Image(); img.src = _src; img.onload = function(){ var $wrap = $('#showSreenShot .wrap'); $wrap.height(_h) $wrap.width(_w) $wrap.css({ marginTop: -_h*2/3, marginLeft: -_w/2 }) $('#showSreenShot .wrap').prepend($(img)); $('#showSreenShot').fadeIn(200); } }
html2canvas.js 下载地址 https://github.com/niklasvh/html2canvas/tree/master/dist