作用
- html2canvas可以通过纯JS对浏览器端经行截屏,但截图的精确度还有待提高,部分css不可识别,所以在canvas中不能完美呈现原画面样式
支持的浏览器
- Firefox 3.5+
- Google Chrome
- Opera 12+
- IE9+
- Safari 6+
基本语法
//两个参数:所需要截图的元素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="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>
效果图
![](https://img.haomeiwen.com/i2206027/a69a8f67edf65bc2.png)
Paste_Image.png
![](https://img.haomeiwen.com/i2206027/cbd223205373a24d.png)
Paste_Image.png
html2canvas官网
网友评论
跟着引入这个就好了,ie11原生不支持es6的一些特性
https://www.toutiao.com/i6615074630862373390/
https://blog.csdn.net/qq_32859565/article/details/83273248
这两个都可以
allowTaint: false, //允许跨域(图片跨域相关)
加上这两个参数
useCORS: true, //(图片跨域相关)
allowTaint: false, //允许跨域(图片跨域相关)
html2canvas(document.getElementById('imgbg'), {
useCORS: true, //(图片跨域相关)
allowTaint: false, //允许跨域(图片跨域相关)
taintTest: true, //是否在渲染前测试图片
onrendered: function(canvas) {
document.getElementById('imgResult').src = canvas.toDataURL();
}
});