March 27, 2019
Javascript: js截图, html转图片(png,jpg), html转canvas, js下载图片,html2canvas截图,html2canvas入门
html2canvas 能够实现在用户浏览器端直接对整个或部分页面进行截屏。这个html2canvas脚本将当页面渲染成一个Canvas图片,通过读取DOM并将不同的样式应用到这些元素上实现。·
它不需要来自服务器任何渲染,整张图片都是在客户端浏览器创建。当浏览器不支持Canvas时,将采用Flashcanvas或ExplorerCanvas技术代替实现。以下浏览器能够很好的支持该脚本:Firefox 3.5+, Google Chrome, Opera新的版本, IE9以上的浏览器。
html2canvas可以通过获取HTML的某个元素,然后生成Canvas,能让用户保存为图片。
这个项目主要是生成canvas,那么我们如果需要生成图片还需要将它转化为图片地址。、
基本语法
html2canvas(element, options);
截取整个页面:
html2canvas(document.body, { onrendered: function(canvas) { var url = canvas.toDataURL();//图片地址 document.body.appendChild(canvas); }, width: 300, height: 300 });
或者使用ES6的promise
//两个参数:所需要截图的元素id,截图后要执行的函数, canvas为截图后返回的最后一个canvas html2canvas(document.getElementById('id')).then(function(canvas) {document.body.appendChild(canvas);});
可用参数
参数名称 | 类型 | 默认值 | 描述 |
---|---|---|---|
allowTaint | boolean | false | Whether to allow cross-origin images to taint the canvas—允许跨域 |
background | string | #fff | Canvas background color, if none is specified in DOM. Set undefined for transparent—canvas的背景颜色,如果没有设定默认透明 |
height | number | null | Define the heigt of the canvas in pixels. If null, renders with full height of the window.—canvas高度设定 |
letterRendering | boolean | false | Whether to render each letter seperately. Necessary if letter-spacing is used.—在设置了字间距的时候有用 |
logging | boolean | false | Whether to log events in the console.—在console.log()中输出信息 |
proxy | string | undefined | Url to the proxy which is to be used for loading cross-origin images. If left empty, cross-origin images won’t be loaded.—代理地址 |
taintTest | boolean | true | Whether to test each image if it taints the canvas before drawing them—是否在渲染前测试图片 |
timeout | number | 0 | Timeout for loading images, in milliseconds. Setting it to 0 will result in no timeout.—图片加载延迟,默认延迟为0,单位毫秒 |
width | number | null | Define the width of the canvas in pixels. If null, renders with full width of the window.—canvas宽度 |
useCORS | boolean | false | Whether to attempt to load cross-origin images as CORS served, before reverting back to proxy–这个我也不知道是干嘛的 |
例子
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>html2canvas example</title> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script> </head> <script type="text/javascript"> function takeScreenshot() { console.log('test'); html2canvas(document.getElementById('view'), { onrendered: function(canvas) { document.body.appendChild(canvas); // 只是显示出来,如果想下载,请参考下面第二个例子 }, // width: 300, // height: 300 }); } </script> <body> <div id="view" style="background:url(test.jpg) 50%; width: 700px; height: 500px;"> <input type="button" value="截图" onclick="takeScreenshot()"> </div> </body> </html>
效果图
图片下载例子:
function takeScreenshot(obj, filename) { html2canvas(obj, { onrendered: function(canvas) { var imgString = canvas.toDataURL("image/png"); var a = document.createElement('a'); a.href = imgString; a.download = (filename?filename:'image')+'.png'; document.body.appendChild(a); a.click(); document.body.removeChild(a); }, }); }
用法:
takeScreenshot(document.getElementById('screenshot'), 'my-first-screenshot');
也有其他实例用了比较负责点的下载方式:
function takeScreenshot() { html2canvas(obj, { onrendered: function(canvas) { save_image(canvas); } }); } //转换png图片 function save_image(canvas) { // 图片导出为 png 格式 var type = 'png'; var imgData = canvas.toDataURL(type); /** * 获取mimeType * @param {String} type the old mime-type * @return the new mime-type */ var _fixType = function(type) { type = type.toLowerCase().replace(/jpg/i, 'jpeg'); var r = type.match(/png|jpeg|bmp|gif/)[0]; return 'image/' + r; }; // 加工image data,替换mime type imgData = imgData.replace(_fixType(type),'image/octet-stream'); /** * 在本地进行文件保存 * @param {String} data 要保存到本地的图片数据 * @param {String} filename 文件名 */ var saveFile = function(data, filename){ var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a'); save_link.href = data; save_link.download = filename; var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); save_link.dispatchEvent(event); }; // 下载后的文件名 var filename = 'screenshots_card_' + (new Date()).getTime() + '.' + type; // download saveFile(imgData,filename); // console.log(filename) }
关于设置背景颜色的问题:
下载图片如果是黑色背景,或者是透明背景,那么看起来就不好看,或者影响视觉,那么根据配置选项,它是支持设置背景颜色的:
html2canvas(document.getElementById("screenshot"), { background: "#fff", onrendered: function(canvas){ // do something } });
但是如果还是不能填充上,那么可以尝试一下修改下载区域的css,例如上面的例子,它的下载区域是 id为screenshot的区域,那么添加css style:
#screenshot{ background-color: white;}
支持的浏览器
- Firefox 3.5+
- Google Chrome
- Opera 12+
- IE9+
- Safari 6+
本文:Javascript: js截图, html转图片(png,jpg), html转canvas, js下载图片,html2canvas截图,html2canvas入门