1、HTML代码
<div id="content">
<div id="header">
<h1>html2canvas - 网页转换为图片</h1>
</div>
<div id="nav">
创建canvas画布<br>
获取文档高宽度<br>
canvas画布放大<br>
设置偏移量<br>
html2canvas插件显示图片及下载<br>
</div>
<div id="section">
<h2>angbike</h2>
<p>
此处省略多少字
</p>
</div>
<div id="footer">
Copyright © W3Schools.com
</div>
</div>
<a href="javascript:;" class="down" download="downImg">图片下载</a>
2、CSS代码
body{
padding: 0px;
margin: 0px;
}
#content{
width: 100%;
}
#header {
background-color:black;
color:white;
text-align:center;
padding:5px;
}
#nav {
line-height:30px;
background-color:#eeeeee;
height:300px;
width:300px;
float:left;
padding:5px;
}
#section {
width:350px;
float:left;
padding:10px;
}
#footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}
.down{
display: table;
border: 1px solid #000;
margin: 10px auto;
color: #fff;
background: #000;
text-decoration: none;
padding: 0px 5px 2px 5px;
border-radius: 5px;
}
3、JavaScript代码
//创建一个新的canvas
var canvas = document.createElement("canvas");
//获取文档中第一个div元素
var _canvas = document.querySelector('div#content');
//获取文档高宽度
var w = parseInt(window.getComputedStyle(_canvas).width);
var h = parseInt(window.getComputedStyle(_canvas).height);
//将canvas画布放大若干倍,然后放在较小的容器内,就显得不模糊了
canvas.width = w * 2;
canvas.height = h * 2;
canvas.style.width = w + "px";
canvas.style.height = h + "px";
//设置偏移量
var context = canvas.getContext("2d");
context.scale(2,2);
//调用html2canvas
html2canvas(document.querySelector('div'),{canvas: canvas}).then(function(canvas) {
//隐藏原始网页
document.getElementById("content").style.display = "none";
//追加canvas到doc
document.body.appendChild(canvas);
//canvas转换成url,然后利用a标签的download属性,直接下载
document.querySelector(".down").setAttribute('href',canvas.toDataURL());
});
注意:此功能基于html2canvas插件,页面需要引入此插件。
插件下载地址:http://html2canvas.hertzen.com/