1

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

我附上了一个显示我状况的小提琴。现在,当您按下按钮时,值为“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 中其他答案的公式。

4

2 回答 2

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.
});
于 2013-05-28T10:32:37.510 回答
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);
});
于 2013-09-22T13:28:44.683 回答