失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > html5手指滑动图片放大缩小 移动端如何实现图片通过捏合手势放大缩小呢?

html5手指滑动图片放大缩小 移动端如何实现图片通过捏合手势放大缩小呢?

时间:2020-07-04 16:36:48

相关推荐

html5手指滑动图片放大缩小 移动端如何实现图片通过捏合手势放大缩小呢?

/*

* @Author 兔爷

* @function 实现单指拖动图片,双指缩放图片

* @marks 参数one是为了区分屏幕上现在是一根手指还是两根手指,因为在滑动的时候两根手指先离开一根会触发一根手指移动图片位置这个方法

*/

var touchScale = function(seletor, bg) {

var startX, endX, scale, x1, x2, y1, y2, imgLeft, imgTop, imgWidth, imgHeight,

one = false,

$touch = $(seletor),

originalWidth = $touch.width(),

originalHeight = $touch.height(),

baseScale = parseFloat(originalWidth/originalHeight),

imgData = [],

bgTop = parseInt($(bg).css('top'));

function siteData(name) {

imgLeft = parseInt(name.css('left'));

imgTop = parseInt(name.css('top'));

imgWidth = name.width();

imgHeight = name.height();

}

$(document).on('touchstart touchmove touchend', $(seletor).parent().selector, function(event){

var $me = $(seletor),

touch1 = event.originalEvent.targetTouches[0], // 第一根手指touch事件

touch2 = event.originalEvent.targetTouches[1], // 第二根手指touch事件

fingers = event.originalEvent.touches.length; // 屏幕上手指数量

//手指放到屏幕上的时候,还没有进行其他操作

if (event.type == 'touchstart') {

if (fingers == 2) {

// 缩放图片的时候X坐标起始值

startX = Math.abs(touch1.pageX - touch2.pageX);

one = false;

}

else if (fingers == 1) {

x1 = touch1.pageX;

y1 = touch1.pageY;

one = true;

}

siteData($me);

}

//手指在屏幕上滑动

else if (event.type == 'touchmove') {

if (fingers == 2) {

// 缩放图片的时候X坐标滑动变化值

endX = Math.abs(touch1.pageX - touch2.pageX);

scale = endX - startX;

$me.css({

'width' : originalWidth + scale,

'height' : (originalWidth + scale)/baseScale,

'left' : imgLeft,

'top' : imgTop

});

}else if (fingers == 1) {

x2 = touch1.pageX;

y2 = touch1.pageY;

if (one) {

$me.css({

'left' : imgLeft + (x2 - x1),

'top' : imgTop + (y2 - y1)

});

}

}

}

//手指移开屏幕

else if (event.type == 'touchend') {

// 手指移开后保存图片的宽

originalWidth = $touch.width(),

siteData($me);

imgData = [[imgLeft, imgTop-bgTop, imgWidth, imgHeight],[0, 0, 640, 640]];

}

});

var getData = function(){

return imgData;

};

return {

imgData : getData

}

};

这是我之前写的单指拖动,双指缩放的js代码,希望对你有所帮助,用前请调用jquery。

如果觉得《html5手指滑动图片放大缩小 移动端如何实现图片通过捏合手势放大缩小呢?》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。