当旋转为0时,获取div的x,y坐标

时间:2013-05-28 02:52:15

标签: javascript math sencha-touch-2 trigonometry

嗨,我需要一些帮助解决我的问题。我有一种情况,每当触发touchstart事件时我都需要访问div的左上角坐标。但我需要根据div的旋转为0度来获得它。

I have attached a fiddle which shows my condition。现在按下按钮时,值为'x:169,y:195'。但我正在寻找一些公式来得到'x:208,y:234'

document.querySelectorAll('input')[0].addEventListener('click',function() {
  var x = Math.round(document.querySelectorAll('#knob')[0].getBoundingClientRect().left),
      y = Math.round(document.querySelectorAll('#knob')[0].getBoundingClientRect().top)
      alert('x: '+x+', y: '+y);

    /* 
     * Alerts x: 208, y: 234 when angle is 0. 
     * Need to get this value all the time irrespective of the rotation.
     */
});

这可能吗?我做了很多搜索,但找不到合适的答案。我的数学不足以修改SO中其他答案的公式。

2 个答案:

答案 0 :(得分:1)

请注意,旋转时红色方块的中心不会改变。所以我们可以先找到它的坐标(取平均值),然后找出左上角(基于红色正方形的大小预先给出的事实;在这种情况下,它是256x256)。这是一个简单的实现:

document.querySelectorAll('input')[0].addEventListener('click',function() {
var left = Math.round(document.querySelectorAll('#knob')[0].getBoundingClientRect().left),
    right = Math.round(document.querySelectorAll('#knob')[0].getBoundingClientRect().right),
    top = Math.round(document.querySelectorAll('#knob')[0].getBoundingClientRect().top),
    bottom = Math.round(document.querySelectorAll('#knob')[0].getBoundingClientRect().bottom),
    x_mid = (left+right)/2.0,
    y_mid = (top+bottom)/2.0,
    x = x_mid - 256/2, // Subtract by half the knob's width.
    y = y_mid - 256/2  // Subtract by half the knob's height.
alert('left: '+left+', right: '+right+', top: '+top+', bottom: '+bottom+'\n'
      +'centre: ('+x_mid+', '+y_mid+')\n'
      +'x: '+x+', y: '+y);

//Alerts x: 208, y: 234 when angle is 0. Need to get this value all the time irrespective of the rotation.
});

答案 1 :(得分:0)

将此代码用于任何数字

document.querySelectorAll('input')[0].addEventListener('click', function () {

var left = Math.round(document.querySelectorAll('#knob')[0].getBoundingClientRect().left),
    right = Math.round(document.querySelectorAll('#knob')[0].getBoundingClientRect().right),
    top = Math.round(document.querySelectorAll('#knob')[0].getBoundingClientRect().top),
    bottom = Math.round(document.querySelectorAll('#knob')[0].getBoundingClientRect().bottom),
    width = Math.round(document.querySelectorAll('#knob')[0].offsetWidth),
    height = Math.round(document.querySelectorAll('#knob')[0].offsetHeight),        
    x_mid = (left + right) / 2.0,
    y_mid = (top + bottom) / 2.0,
    x = x_mid - width / 2, // Subtract by half the knob's width.
    y = y_mid - height / 2 // Subtract by half the knob's height.
alert('left: ' + left + ', right: ' + right + ', top: ' + top + ', bottom: ' + bottom + '\n' + 'centre: (' + x_mid + ', ' + y_mid + ')\n' +'dimen; w:' +width + ',h:'+ height + 'x: ' + x + ', y: ' + y);
});