一個比較有意思的縮放旋轉實現

function setGesture(el){
    var obj={}; //定義一個對象
    var istouch=false;
    var start=[];
    el.addEventListener("touchstart",function(e){
        if(e.touches.length>=2){  //判斷是否有兩個點在屏幕上
            istouch=true;
            start=e.touches;  //得到第一組兩個點
            obj.gesturestart&&obj.gesturestart.call(el); //執行gesturestart方法
        };
    },false);
    document.addEventListener("touchmove",function(e){
        e.preventDefault();
        if(e.touches.length>=2&&istouch){
            var now=e.touches;  //得到第二組兩個點
            var scale=getDistance(now[0],now[1])/getDistance(start[0],start[1]); //得到縮放比例,getDistance是勾股定理的一個方法
            var rotation=getAngle(now[0],now[1])-getAngle(start[0],start[1]);  //得到旋轉角度,getAngle是得到夾角的一個方法
            e.scale=scale.toFixed(2);
            e.rotation=rotation.toFixed(2);
            obj.gesturemove&&obj.gesturemove.call(el,e);  //執行gesturemove方法
        };
    },false);
    document.addEventListener("touchend",function(e){
        if(istouch){
            istouch=false;
            obj.gestureend&&obj.gestureend.call(el);  //執行gestureend方法
        };
    },false);
    return obj;
};
function getDistance(p1, p2) {
    var x = p2.pageX - p1.pageX,
        y = p2.pageY - p1.pageY;
    return Math.sqrt((x * x) + (y * y));
};
function getAngle(p1, p2) {
    var x = p1.pageX - p2.pageX,
        y = p1.pageY- p2.pageY;
    return Math.atan2(y, x) * 180 / Math.PI;
};


var box=document.querySelector("#box");
    var boxGesture=setGesture(box);  //得到一個對象
    boxGesture.gesturestart=function(){  //雙指開始
        box.style.backgroundColor="yellow";
    };
    boxGesture.gesturemove=function(e){  //雙指移動
        box.innerHTML = e.scale+"<br />"+e.rotation;
        box.style.transform="scale("+e.scale+") rotate("+e.rotation+"deg)";//改變目標元素的大小和角度
    };
    boxGesture.gestureend=function(){  //雙指結束
        box.innerHTML="";
        box.style.cssText="background-color:red";
    };

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章