2015/Spring 跨平台行動程式進階應用 王派洲老師 pwang@mail.stust.edu.tw, Office:L306-2, Tel:2533131 Ext.4327
課程大綱 HTML5 Canvas Touch事件
Canvas <canvas>畫布標籤用於圖片繪製 <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"> </canvas>
File套件 安裝 cordova plugin add org.apache.cordova.file
Canvas-2 var cav=document.getElementById('myCanvas'); var ctx = cav.getContext('2d'); ctx.fillStyle = "#FF0000"; ctx.fillRect(0,0,150,75);
Canvas drawImage drawImage(img,x,y) drawImage(img,x,y,width,height) 將圖片顯示於canvas座標(x,y)上 drawImage(img,x,y,width,height) 將圖片以width,height大小顯示於canvas座標(x,y)上 drawImage(img,sx,sy,swidth,sheight,x,y,width,height)
Canvas drawImage drawImage(img,x,y) function onImage1Load() { 將圖片顯示於canvas座標(x,y)上 function onImage1Load() { ctx.drawImage(img,0,0); } receivedEvent: function(id) { can = document.getElementById('myCanvas'); ctx=can.getContext('2d'); img=new Image(); img.onload = onImage1Load; img.src= "img/htc.jpg";
沒有設定Canvas大小 drawImage(img,x,y) function onImage1Load() { 將圖片顯示於canvas座標(x,y)上 function onImage1Load() { ctx.drawImage(img,0,100); } receivedEvent: function(id) { can = document.getElementById('myCanvas'); ctx=can.getContext('2d'); img=new Image(); img.onload = onImage1Load; img.src= "img/htc.jpg";
設定Canvas大小 drawImage(img,x,y) function onImage1Load() { 將圖片顯示於canvas座標(x,y)上 function onImage1Load() { ctx.drawImage(img,0,100); } receivedEvent: function(id) { can = document.getElementById('myCanvas'); ctx=can.getContext('2d'); img=new Image(); img.onload = onImage1Load; img.src= "img/htc.jpg";
Canvas drawImage drawImage(img,x,y,width,height) 將圖片以width,height大小顯示於canvas座標(x,y)上 function onImage1Load() { ctx.drawImage(img,0,0,100,100); } receivedEvent: function(id) { can = document.getElementById('myCanvas'); ctx=can.getContext('2d'); img=new Image(); img.onload = onImage1Load; img.src= "img/htc.jpg";
Canvas drawImage drawImage(img, sx, sy, sw, sh, dx, dy, w, h) 選擇原始圖片sx,sy位置開始sw與sh寬與高,顯示 於canvas dx,dy位置以w,h寬與高顯示 function onImage1Load() { ctx.drawImage(img, 30,50,150,50,20,20,150,50); } receivedEvent: function(id) { can = document.getElementById('myCanvas'); ctx=can.getContext('2d'); img=new Image(); img.onload = onImage1Load; img.src= "img/htc.jpg";
Touch event(多點) touchstart 代表一個新的touch發生,事件中的changedTouches包含事件發生時所有的接觸點,changedTouches中的 每個touch包含屬性identifier, pageX, pageY 執行事件處理時必須先執行event.preventDefault() 其目的是避免程式繼續執行其他touch事件 function onStart(evt) { evt.preventDefault(); var touches=evt.changedTouches; alert("X:"+touches[0].pageX+", Y:"+touches[0].pageY); } receivedEvent: function(id) { can = document.getElementById('myCanvas'); ctx=can.getContext('2d'); can.width=screen.width; can.height=screen.height; can.addEventListener("touchstart",function(evt){onStart(evt);},false);
Touch event(多點) touchmove 代表一個新的touch移動發生,事件中的changedTouches包含事件發生時所有的接觸點,每個touch 中pageX與pageY代表移動至位置 執行事件處理時必須先執行event.preventDefault() 其目的是避免程式繼續執行其他touch事件 練習: 利用Canvas、moveTo、lineTo、stroke()、touchstart、touchmove製作簡單手指繪圖APP
Puzzle拼圖