使用array和setInterval计算转换

时间:2015-12-23 18:25:29

标签: jquery

我正在尝试创建一个移动元素,它从该元素的数据字段中获取所有必需的信息。使用javascript我创建数组并通过它们列出以获取所需的信息。我设法让它工作,但现在我遇到setInterval使用i变量不接受间隔更改的问题。它必须将间隔更改为等于时间数组项的差异,但它始终为1秒。有关如何使其正常工作的任何想法?提前谢谢。



var xPos = $('.coord-dot').attr('data-x'); // get x coordinate of the point
var yPos = $('.coord-dot').attr('data-y'); // get y coordinate of the point
var time = $('.coord-dot').attr('data-time'); // timestamp input string
xArr = xPos.split(','); // split x coordinates into an array
yArr = yPos.split(','); // split y coordinates into an array
timeArr = time.split(','); // split time into an array

var i = 1;
var n = 0;

window.setInterval(function() {
  n = timeArr[i] - timeArr[i - 1]; // calculate the difference between next and current aray items
  i = i + 1;
  $('.coord-dot').css('transition', timeArr[n] + 's');
  $('.coord-dot').css('transform', 'translate(' + xArr[i - 1] + 'px,' + yArr[i - 1] + 'px)');
}, i * 1000);

.coord-dot {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="coord-dot" data-x="0,20,15,150,50" data-y="150,0,40,75,50" data-time="0,6,9,10,14">
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

考虑window.requestAnimationFrame()

https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

不是告诉JS在X秒内运行一个函数,而是不断运行,并检查X秒过去的时间。这使您可以控制如何处理时序冲突,并且性能更高。

https://dev.opera.com/articles/better-performance-with-requestanimationframe/

&#13;
&#13;
var $dot = $('.coord-dot'),
  xPos = $dot.attr('data-x'), // get x coordinate of the point
  yPos = $dot.attr('data-y'), // get y coordinate of the point
  time = $dot.attr('data-time'), // timestamp input string
  xArr = xPos.split(','), // split x coordinates into an array
  yArr = yPos.split(','), // split y coordinates into an array
  timeArr = time.split(','); // split time into an array


var n = 0; // current step (array index)
var start = null; // for checking duration



function step(timestamp) {
  if (!start) start = timestamp;
  var progress = timestamp - start;

  if (n <= timeArr.length) {
    window.requestAnimationFrame(step);

    if (progress >= timeArr[n] * 1000) {
      console.log(n, timeArr[n], xArr[n], yArr[n]);

      $('.coord-dot').css('transition', timeArr[n] + 's');
      $('.coord-dot').css('transform', 'translate(' + xArr[n] + 'px,' + yArr[n] + 'px)');

      n++;
    }
  }

}

window.requestAnimationFrame(step);
&#13;
.coord-dot {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="coord-dot" data-x="0,20,15,150,50" data-y="150,0,40,75,50" data-time="0,1,2,3,4">
</div>
&#13;
&#13;
&#13;