根據(jù)html2canvas官方文檔的介紹,html2canvas庫的工作原理并不是真正的“截圖”正驻,而是讀取網(wǎng)頁上的目標(biāo)DOM節(jié)點(diǎn)的信息來繪制canvas,所以它并不支持所有的css屬性(詳情參考這里)哎榴,而且期望使用的圖片跟當(dāng)前域名同源琼蚯,不過官方也提供了一些方法來解決跨域圖片的加載問題。
其使用方法很簡單谋竖,引入html2canvas庫以后红柱,拿到目標(biāo)dom調(diào)用一下html2canvas方法就能生成canvas對(duì)象了承匣,由于我們的目標(biāo)是生成圖片,所以還需要再調(diào)用canvas.toDataURL()方法生成<img>標(biāo)簽的可用數(shù)據(jù):
基本語法:
html2canvas(element, options);
html2canvas(document.body, {
onrendered: function(canvas) {
var url = canvas.toDataURL();//圖片地址
document.body.appendChild(canvas);
},
width: 300,
height: 300
});
或者使用ES6的promise:
html2canvas(document.querySelector('.detail-box')).then(function(canvas) {
var url = canvas.toDataURL();//圖片路徑
this.imgUrl = url;
});
可用參數(shù)
參數(shù)名稱 | 類型 | 默認(rèn)值 | 描述 |
---|---|---|---|
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的背景顏色锤悄,如果沒有設(shè)定默認(rèn)透明 |
height | number | null | Define the heigt of the canvas in pixels. If null, renders with full height of the window.---canvas高度設(shè)定 |
letterRendering | boolean | false | Whether to render each letter seperately. Necessary if letter-spacing is used.---在設(shè)置了字間距的時(shí)候有用 |
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.---圖片加載延遲韧骗,默認(rèn)延遲為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--這個(gè)我也不知道是干嘛的 |
例子:
<!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="html2canvas.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>
參考文案:
http://www.reibang.com/p/22bd5b98e38a
http://www.reibang.com/p/6a07e974a7e8