Pinchzoom

by Terry King

HTML

<div id="container">Pinch zoom - click image to reset<div id="results"></div><img id="image" src="http://upload.wikimedia.org/wikipedia/commons/7/75/Canary_Wharf_at_night,_from_Shadwell.jpg"  /><div id="marker"></div></div>
<div id="fgDiv"></div>

CSS

#marker{
	background-color:#0F0;
	position:absolute;
	left:50px;
	top:50px;
	width:5px;
	height:5px;
	border-radius:5px;
}
#container{
	position:absolute;
	left:0;
	right:0;
	top:0;
	bottom:0;
	opacity:1;
	overflow:hidden;
}
#fgDiv{
	position:absolute;
	left:0;
	right:0;
	top:0;
	bottom:0;
	background-color:#F00;
	opacity:0;
}

JavaScript

var touchDist;
	var imageW,imageH;
	var pinchX,pinchY;
	var offsetX,offsetY;
	var o_screenX,o_screenY,o_clientX,o_clientY;	
	var zooming=false;
	var mode=0;
	var touchTime;

	function touchstart(e){
		touchTime=new Date().valueOf();
		if (e.touches.length==1){
			mode=1;
		  var imageTop = $('#image').position().top;
		  var imageLeft = $('#image').position().left;
		  offsetX = e.touches[0].clientX-imageLeft;
		  offsetY = e.touches[0].clientY-imageTop;
		}
		if (e.touches.length==2){
			mode=2;
		  var dx = e.touches[0].screenX-e.touches[1].screenX;
		  var dy = e.touches[0].screenY-e.touches[1].screenY;
		  pinchX = e.touches[0].clientX+(e.touches[1].clientX-e.touches[0].clientX)/2; 
		  pinchY = e.touches[0].clientY+(e.touches[1].clientY-e.touches[0].clientY)/2; 
		  var imageTop = $('#image').position().top;
		  var imageLeft = $('#image').position().left;
		  offsetX = pinchX-imageLeft;
		  offsetY = pinchY-imageTop;
		  touchDist = Math.sqrt((dx*dx)+(dy*dy));
		  $('#marker').css({left:pinchX+'px',top:pinchY+'px'}).show();

		  imageW=$('#image').width();
		  imageH=$('#image').height();
		  e.preventDefault();
		  e.stopPropagation();		  
		  return false;
	  }
	}
	
	function touchmove(e){
		if (e.touches.length==1 && mode==1){
			ox=e.touches[0].clientX-offsetX;
			oy=e.touches[0].clientY-offsetY;
			$('#image').css({position:'absolute',left:ox+'px',top:oy+'px'});
			e.preventDefault();
			e.stopPropagation();		  
			return false;
		}
	  if (e.touches.length==2 && mode==2){
		  var dx = e.touches[0].screenX-e.touches[1].screenX;
		  var dy = e.touches[0].screenY-e.touches[1].screenY;
		  var touchDist2 = Math.sqrt((dx*dx)+(dy*dy));
		  var scale = (((touchDist2/touchDist)-1)*1)+1;
		  var ox=(pinchX)-(offsetX*scale);
		  var oy=(pinchY)-(offsetY*scale);
//		  $('#results').text(ox+','+oy);
		  $('#image').css({position:'absolute',left:ox+'px',top:oy+'px',width:(imageW*scale)+'px',height:(imageH*scale)+'px'});
		  e.preventDefault();
		 ...