先分析下这个技术可实现的方式,以及优缺点吧!
前端实现
缺点是:兼容性查,需要高级浏览器支持,因为需要支持 canvas 绘图,还有就是会操作 html5 canvas api。(如果不会使用canvas的话,要么去学,要么这条方案当我没说)
优点是:用户体验性很赞,很流畅。
大体实现方法:使用canvas。最终可将绘制的图像生成成图片。用户可以另存为保存,也可以将生成的二进制图片,上传服务器,生成连接。
后端实现
缺点是:体验性会差很多,因为需要和服务器交互,体验流畅度会差一点。 优点:客户端兼容性好,基本支持所有浏览器。
大体方法:前端负责组织数据。后端负责根据数据生成图片。后端解决的话就比较简单了,有了数据买就是把位置对好,生成图片,就行了。 nodejs, python, java, php 都用很多绘图库。
具体实现流程这里就不废话了。点到为止。下面便是具体的代码实现
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script type="text/javascript" src="http://www.boolaw.com/tpl/default/js/jquery-1.8.3.min.js"></script>
<title>html2canvas网页截图</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- html2canvas()中,第一个参数是要截图的Dom对象,第二个参数时渲染完成后回调的canvas对象。 -->
<script type="text/javascript">
$(function(){
print();
});
function print(){
html2canvas( $("#canv") ,{
onrendered: function(canvas){
$('#down_button').attr( 'href' , canvas.toDataURL() ) ;
$('#down_button').attr( 'download' , 'myjobdeer.png' ) ;
var html_canvas = canvas.toDataURL();
$.post('', {order_id:1,type_id:2,html_canvas:html_canvas}, function(json){
}, 'json');
}
});
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="canv">
此网页演示了html2canvas截图后将截图后的网页追加到了原网页之上 <br> <br>
这里可以看作是边界线 <hr/>
</div>
<a type="button" id="down_button">下载</a>
<?php
if (isset($_POST['html_canvas'])) {
$order_id = $_POST['order_id'];
$type_id = $_POST['type_id'];
$html_canvas = $_POST['html_canvas'];
$image = base64_decode(substr($html_canvas, 22));
header('Content-Type: image/png');
$filename = $order_id . '-' . $type_id . ".png";
$fp = fopen($filename, 'w');
fwrite($fp, $image);
fclose($fp);
}
?>
</body>
</html>