简体   繁体   中英

how to implement pinch zoom in zoom out in js

I am trying to implement pinch zoom in zoom out in js. I am almost there, as I have calculated how to detect pinch zoom in zoom out in js using touch events.

 var dist1=0; function start(ev) { if (ev.targetTouches.length == 2) {//check if two fingers touched screen dist1 = Math.hypot( //get rough estimate of distance between two fingers ev.touches[0].pageX - ev.touches[1].pageX, ev.touches[0].pageY - ev.touches[1].pageY); } } function move(ev) { if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) { // Check if the two target touches are the same ones that started var dist2 = Math.hypot(//get rough estimate of new distance between fingers ev.touches[0].pageX - ev.touches[1].pageX, ev.touches[0].pageY - ev.touches[1].pageY); //alert(dist); if(dist1>dist2) {//if fingers are closer now than when they first touched screen, they are pinching alert('zoom out'); } if(dist1<dist2) {//if fingers are further apart than when they first touched the screen, they are making the zoomin gesture alert('zoom in'); } } } document.getElementById ('zoom_here').addEventListener ('touchstart', start, false); document.getElementById('zoom_here').addEventListener('touchmove', move, false);
 <div class='zoom_here'></div>

now i want to translate the img as we keep zoom in

You can try to add transform: scale();`

 var dist1=0; function start(ev) { if (ev.targetTouches.length == 2) {//check if two fingers touched screen dist1 = Math.hypot( //get rough estimate of distance between two fingers ev.touches[0].pageX - ev.touches[1].pageX, ev.touches[0].pageY - ev.touches[1].pageY); } } function move(ev) { if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) { // Check if the two target touches are the same ones that started var dist2 = Math.hypot(//get rough estimate of new distance between fingers ev.touches[0].pageX - ev.touches[1].pageX, ev.touches[0].pageY - ev.touches[1].pageY); //alert(dist); if(dist1>dist2) {//if fingers are closer now than when they first touched screen, they are pinching x/2 alert('zoom out'); img.style.transform = 'scale('+x+')' } if(dist1<dist2) {//if fingers are further apart than when they first touched the screen, they are making the zoomin gesture 2*x alert('zoom in'); img.style.transform = 'scale('+x+')' } } } var x = 1 var img = document.getElementById ('zoom_here') document.getElementById ('zoom_here').addEventListener ('touchstart', start, false); document.getElementById('zoom_here').addEventListener('touchmove', move, false);

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM