2011年4月6日 星期三

iphone safari 多點觸控實作

參考一
http://developer.apple.com/library/safari/#documentation/appleapplications/reference/safariwebcontent/HandlingEvents/HandlingEvents.html
參考二
http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html#//apple_ref/doc/uid/TP40008193-SW1

來製作一個二指劃開後圖片隨二指距離而變化

製作多點觸控,為避免瀏覽器的zoom in zoom out干擾所以要先將zoom的功能關閉

實作範例教學:
<meta name="viewport" content="width=device-width,height=420, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=0"/>   



圖片替換用的 div
<div id="img"><img src="1.png" width="320"></div>



加上感應觸控的 div
<div id="touch" ontouchstart="touchStart(event);" ontouchmove="touchMove(event);" ontouchend="touchEnd(event);" ontouchcancel="touchCancel(event);"></div>



css

html body{
    overflow: hidden;
}
#touch{
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background-color:#AAAAAA;
    opacity: 0;
}
#img{
    position:absolute;
    top:0;
    left:0;
}



javascript

//預先載入五張圖片
var img1 = new Image(); img1.src = '1.png';
var img2 = new Image(); img2.src = '2.png';
var img3 = new Image(); img3.src = '3.png';
var img4 = new Image(); img4.src = '4.png';
var img5 = new Image(); img5.src = '5.png';

var x_percent = 1; //二點距離指數
//加入觸控event
element.addEventListener("touchstart", touchStart, false);
element.addEventListener("touchmove", touchMove, false);
element.addEventListener("touchend", touchEnd, false);
element.addEventListener("touchcancel", touchCancel, false);

function touchStart(event){
//event 開時換第一張圖
    x_percent = 1;
    changeImg(x_percent);
}
function touchMove(event){
//依二指距離替換五張圖
    var x1 = event.touches[0].pageX;
    var y1 = event.touches[0].pageY;
    var x2 = event.touches[1].pageX;
    var y2 = event.touches[1].pageY;
    var x_diff = Math.abs(x1-x2);
    x_percent = Math.ceil((x_diff/32)/2);
    changeImg(x_percent);
}
function touchEnd(event){
//結束換回第一張圖
    x_percent = 1;
    changeImg(x_percent);
}
function touchCancel(event){
//取消也是換回第一張圖
    x_percent = 1;
    changeImg(x_percent);
}
function changeImg(screen){
    if(screen > 5){
        screen = 5;
    }
    if(screen < 1){
        screen = 1;
    }
    document.getElementById("img").innerHTML = '<img src="'+screen+'.png" width="320">';
}


結果展示:http://excite.978.tw/iphone/mtouch.php
(要用iphone的Safari開啟)
然後二指左右劃開就可以看到效果

沒有留言:

張貼留言