昨天写了一篇《 JavaScript: 让拖动支持iphone/ipad触摸 》,今天又无聊,想到了图片放大(zoom),让使用ios设备的的用户可以使用两根手指来缩放图片。想了一下,很容易就实现了。
其实原理也就是在图片接收了两个有效触摸点后,在手指移动过程中检测两点之间的距离的变化,以此来对图片进行放大缩小。
不多说,demo在这里(必须使用ios设备查看)。代码如下:
var getZoomClass=(function(){
var SupportsTouches = ("createTouch" in document),//判断是否支持触摸
$=function(id){
return document.getElementById(id);
},
preventDefault=function(ev){
if(ev)ev.preventDefault();
else window.event.returnValue = false;
},
getTwoPointSub=function(ev){
var x1=x2=y1=y2=0,sub;
x1=ev.touches.item(0).pageX;x2=ev.touches.item(1).pageX;
y1=ev.touches.item(0).pageY;y2=ev.touches.item(1).pageY;
sub=Math.round(Math.sqrt(Math.pow(x1-x2,2)+Math.pow(y1-y2,2)));
return sub;
},
getSize=function(img){
return {width:img.width,height:img.height};
};
function _zoom(opt){
if(!SupportsTouches)return false;
this.el=typeof opt.el=='string'?$(opt.el):opt.el;
this.onstart=opt.start || new Function();//
this.onmove=opt.move || new Function();
this.onend=opt.end || new Function();
this.action=false;
this.init();
}
_zoom.prototype={
init:function(){
this.el['ontouchstart']=this.bind(function(e){//绑定节点的 [鼠标按下/触摸开始] 事件
if(this.action || e.touches.length<2)return false;//这里监测了触摸点的数量,小于两个说明不是在进行缩放操作
else this.action=true;
preventDefault(e);
this.startSub=getTwoPointSub(e);
this.startSize=getSize(this.el);
this.onstart();
document.ontouchmove=this.bind(function(e){
if(e.touches.length>1){
preventDefault(e);//取消文档的默认行为[鼠标移动、触摸移动]
this.nowSub=getTwoPointSub(e);
this.el.width=this.startSize.width*this.nowSub/this.startSub;
this.el.height=this.startSize.height*this.nowSub/this.startSub;
this.onmove();
}
},this);
document.ontouchend=document.ontouchcancel=this.bind(function(){
document.ontouchend=document.ontouchcancel=document.ontouchmove=null;
this.action=false;
this.onend();
},this);
},this);
},
bind:function(fn,obj){
return function(){
fn.apply(obj,arguments);
}
},
tool:null
}
return function(opt){
return new _zoom(opt);
}
})();
demo在这里(必须使用ios设备查看)。