先分析下這個技術可實現的方式,以及優缺點吧!
前端實現
缺點是:兼容性查,需要高級瀏覽器支持,因為需要支持 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>
