2013年3月20日 星期三

以html2canvas制作頁面截圖列印

網上有很多截圖的Service, 如webkit2pngkhtml2png,但始終也要經過第三方處理,對於一些內部應用好像不太方便。

HTML2CANVAS是完全以Client Side Javascript 來將網頁截圖,由於需要用到HTML5的CANVAS ELEMENT,所以對瀏覽器有一定要求,例如 IE9以下並不支援 (但不知道如果用EXCANVAS可否彌補瀏覽器支援上的不足,稍後再試吧)。

HTML2CANVAS
官方:http://html2canvas.hertzen.com/
下載:https://github.com/niklasvh/html2canvas

開始編寫時在官方下載了0.34版本,使用時發現 IE9可正常運行,但Chrome只能於ready時執行,而無法由button click event執行。後來改用了0.4版本,卻輪到 IE不行。接著發現其中的renderElement function 中有null value的error, 修改後IE終於亦可正常運作了。

紅色為html2canvas.js新增部份
case "INPUT":
        if (/^(text|url|email|submit|button|reset)$/.test(element.type) && (element.value || element.placeholder || "").length > 0){
          renderFormValue(element, bounds, stack);
        }

亦可下載修改後的html2canvas.js :
https://docs.google.com/file/d/0B9ookpf4ArZcMHhqemVkTzBCVlU/edit?usp=sharing

例子: index.html(http://plnkr.co/edit/VR30GO)
<!doctype html>
<html>
<head>
  <script src="jquery.js"></script> <!-- version: 1.9.1 -->
  <script src="html2canvas.js"></script> <!-- version: 0.4.0 modify -->
</head>
<body>
  <h1>Example</h1>
  <pre>HTML2CANVAS to new window and print</pre>
  <button class="print">Print</button>
  <!-- Button event must after button element, it is not run insert ready() -->
  <script>
   $(".print").on("click", function(event) {
 html2canvas($('body'), {
  onrendered: function(canvas) {
    var newWind=window.open('', "Print");
    <!-- Must use html5 -->
    newWind.document.write("<!doctype html><html><body><img src='"+canvas.toDataURL()+"'/></body></html>");
    newWind.print();
   }
 });
  });
  </script>
</body>
</html>

File Download (include index.html, html2canvas.js, jquery.js):
https://docs.google.com/file/d/0B9ookpf4ArZcSlB2OXN4c1pGQ00/edit?usp=sharing

2013年3月13日 星期三

無意中發現的AngularJS

因為尋找關於NodeJS的資料,無意中發現了AngularJS, 感覺其中的雙向綁定功能很方便, 好像在JS中的變數改動就可以即時反映於頁面上, 不同於以住JAVASCRIPT的方式, 需要如set value般設定。

傳統的動態頁面, 如需將兩個TEXTBOX VALUE相加並立即顯示其結果, 其寫法大約如下:
<html>

 <script>

 function cal(val1, val2,output){

  if(val1.value && val2.value)

   output.innerHTML = parseInt(val1.value,10) + parseInt(val2.value,10);

 }

 </script>

 <input id="v1" onChange="cal(this, document.getElementById('v2'),document.getElementById('div1'));"/>+

 <input id="v2" onChange="cal(document.getElementById('v1'),this,document.getElementById('div1'));"/>

 =<div id="div1"></div>

</html>

測試: http://plnkr.co/edit/nZOab3Z9TSp4jlvJKwhW

使用AngularJS:
<!DOCTYPE html>

<html ng-app>

  <head>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>

  </head>

  <body>

    <input type="number" ng-model="v1"/>+

    <input type="number"ng-model="v2"/>

    = {{v1  + v2}}

  </body>

</html>

測試: http://plnkr.co/edit/vGeeBFOaXDpcfIsZh60f


其他關於模版,MVC設計等仍在研究中....

更多關於AngularJS:
http://angularjs.org/

中文社區:
http://www.angularjs.cn

還有類似JQUERY UI的AngularJS UI:
http://angular-ui.github.com/

因為經常會用到Grid, JQUERY有Datatable, 還算易用, 而Angular 的ng-grid好像也相當不錯
http://angular-ui.github.com/ng-grid/