這次來看一下怎麼把上次的HTML5畫圖板使用PhoneGap移植到Andriod上去。經過上一篇的PhoneGap環境的搭建,很輕鬆的就把一個HTML5的web應用移植到了Andriod上去,可以看出PhoneGap的強大。
1.添加自訂的JavaScript檔案index.js
在www檔案夾下添加js檔案夾,在js檔案夾下添加index.js
這裡我重構了上一次的畫板的JavaScript檔案,不過代碼的關鍵點是全部一樣的。我只不過是按照物件導向的方式重構了一下代碼。正好學習JavaScript怎麼實現一個類,怎麼調用方法等,挺有意思的。
function App(){ var _this=this; _this.initialize=function() { //註冊裝置初始化完成事件 document.addEventListener("deviceready", onDeviceReady, false); } var onDeviceReady=function() { var can = new Can(); can.bindEvents();//綁定事件 }}function Can (){var _this=this;var lastX;//最後一次觸摸的x座標var lastY;//最後一次觸摸的y座標var canvas = document.getElementById("canvas");var context =canvas.getContext("2d");var init=function(){ lastX=0; lastY=0; //全屏canvas canvas.width=window.screen.width; canvas.height=window.screen.height; context.lineWidth=10;//畫筆粗細 context.strokeStyle="#FF0000";//畫筆顏色};//綁定事件_this.bindEvents = function() { try { //註冊監聽 canvas.addEventListener('touchstart', onTouchStart, false); canvas.addEventListener('touchmove', onTouchMove, false); } catch(err) { alert(err.message); }};//觸摸開始var onTouchStart=function(){ try { event.preventDefault(); lastX=event.touches[0].clientX; lastY=event.touches[0].clientY; //畫點 drawRound(lastX,lastY); } catch(err) { alert(err.message); }};//觸摸移動var onTouchMove=function(){ try { event.preventDefault(); //畫線 drawLine(lastX,lastY,event.touches[0].clientX,event.touches[0].clientY); lastX=event.touches[0].clientX; lastY=event.touches[0].clientY; } catch(err) { alert( err.message); }};//畫圓var drawRound = function (x,y){ try { context.fillStyle="#FF0000"; context.beginPath(); context.arc(x,y,5,0,Math.PI*2,true); context.closePath(); context.fill(); } catch(err) { alert(err.message); } };//畫線var drawLine = function (startX,startY,endX,endY){ try { context.beginPath(); context.lineCap="round"; context.moveTo(startX,startY); context.lineTo(endX,endY); context.stroke(); } catch(err) { alert(err.message); } };init();} ;
2.修改index.html
這個html代碼跟上次的web應用完全一樣。只添加了對App類的初始化代碼。
<!doctype html><html><head> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> <title>HTML5Paint</title> <script src="http://debug.phonegap.com/target/target-script-min.js#6CFB7EA06AB04AFBB33FD97AE40691C5"></script> <script type="text/javascript" src="cordova-2.6.0.js" charset="utf-8"></script> <script type="text/javascript" src="js/index.js" charset="utf-8"></script> <script type="text/javascript"> try { var app=new App(); app.initialize();//初始化 } catch(err) { alert(err.message); } </script></head><body> <canvas id="canvas" ></canvas></body></html>
3.在Andriod上的效果
這次移植過程可以看到是相當的輕鬆,幾乎是原封不動的就把一個web用移植到了Andriod上去。所花費的成本真的很小很小,phoneGap真的是個很有前途的東西。