Javascript、css:将变换原点更改为gesturechange的中心点

3

我希望将变换原点更改为捏合手势的中心点。

这段工作代码(safariDevSample)应用缩放和旋转,而不更改transform-origin

window.angle = 0; //global to store data for later reset ....
var newAngle;

window.scale = 1;
var newScale;

function saveChanges() {
    window.angle = newAngle;
    window.scale = newScale;
}

function getAngleAndScale(e) {
    // Don't zoom or rotate the whole screen
    e.preventDefault();

    newAngle = window.angle + e.rotation;

    newScale = window.scale * e.scale;

    if (newScale < 1) newScale = 1; //prepend to scale smaller then parent

    // Combine scale and rotation into a single transform
    var tString = "rotate(" + newAngle + "deg) scale(" + newScale + ")";
    document.getElementById("theImg").style.webkitTransform = tString;

}

function init() {
    document.getElementById("theImg").addEventListener("gesturechange", getAngleAndScale, false);
    document.getElementById("theImg").addEventListener("gestureend", saveChanges, false);
}

init();

我尝试使用touchstartgesturestart screenX screenY作为额外的事件监听器,但没有成功。

1个回答

1

我发现通过使用touchstart事件找到了一个可行的解决方案。 首先获取一个固定的转换起点,然后将其转换为相对起点。 这样可以在每个捏合操作中使用...

var yO = 50; 
var xO = 50; 

window.scale = 1;

var newScale; 


function saveChanges() {



    window.scale = newScale;
}


function getTouchStartXY(e){

myTouchStartNullX =  e.touches[0].pageX;
myTouchStartNullY =  e.touches[0].pageY;

myTouchStartSecondX =  e.touches[1].pageX;
myTouchStartSecondY =  e.touches[1].pageY;

myTouchStartX = (myTouchStartNullX + myTouchStartSecondX)/2;
myTouchStartY = (myTouchStartNullY + myTouchStartSecondY)/2;

   var boundingBox = document.getElementById('theImg').getBoundingClientRect();
        picX = boundingBox.left;
  picY = boundingBox.top;
  picRight = boundingBox.right;
    picBottom = boundingBox.bottom;

  if(picX < 0 )picX = picX* (-1);
    if(picY < 0 )picY = picY* (-1);
    xO = ((picX + myTouchStartX)/(picX + picRight))*100;
    yO = ((picY + myTouchStartY)/(picY + picBottom))*100;


     document.getElementById("theImg").style['webkitTransformOrigin'] = xO + '% ' + yO + '%';  

}

function getAngleAndScale(e) {

     // Don't zoom or rotate the whole screen

    e.preventDefault();

      newScale = window.scale * e.scale;
//if(newScale < 1)newScale = 1;





    // Combine scale and rotation into a single transform

    var tString = "scale(" + newScale + ")";

    document.getElementById("theImg").style['webkitTransform'] = tString;

}




function init() {
    document.getElementById("theImg").addEventListener("touchstart", getTouchStartXY, false);

    document.getElementById("theImg").addEventListener("gesturechange", getAngleAndScale, false);
    document.getElementById("theImg").addEventListener("gestureend", saveChanges, false);

}

init();

谢谢

汉斯


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接