最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Moving a div in a webpage at perfect constant speed - Stack Overflow

programmeradmin2浏览0评论

I would like to move a div at a perfect constant speed.

The following project shows my implementation

ponent.html

The code used to move is

setInterval(() => {
  const currentTop = parseInt(this.movingDiv!.style.top || '0', 10);
  this.movingDiv!.style.top = `${currentTop - 1}px`;
}, frameInterval);

It works but have lags, and even more lags and freeze when the browser have other tasks to do on an other page.

I would like to improve the smoothness if possible, and if not, keep the div sync to background music, because it slow down when lagging.

I would like to move a div at a perfect constant speed.

The following project shows my implementation

https://stackblitz/edit/angular-6x9fejz3?file=src%2FAnimationPage%2Fanimationponent.html

The code used to move is

setInterval(() => {
  const currentTop = parseInt(this.movingDiv!.style.top || '0', 10);
  this.movingDiv!.style.top = `${currentTop - 1}px`;
}, frameInterval);

It works but have lags, and even more lags and freeze when the browser have other tasks to do on an other page.

I would like to improve the smoothness if possible, and if not, keep the div sync to background music, because it slow down when lagging.

Share Improve this question edited Mar 18 at 21:46 Foxhunt asked Mar 14 at 16:51 FoxhuntFoxhunt 9222 gold badges13 silver badges31 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

What you probably want to do is calculate a frametime delta in each iteration and use that to properly offset the div. The frametime delta is basically just the amount of time that has passed since the last time you moved the div. Use that value as a factor when offsetting the div and it will make sure the div moves at a constant rate.

This doesn't get rid of any potential lag, it just makes sure that the div moves the same amount of pixels per unit of time. (When there is a lag, the frametime delta is higher, thus the div offset is larger, cancelling out the lag).

An example implementation would be:

  let previousTime = Date.now();

  while (true) {  // your application loop
    let now = Date.now();
    let delta = now - previousTime;  // this is the number of milliseconds since last update

    // I lifted this from your example
    const currentTop = parseInt(this.movingDiv!.style.top || '0', 10);
    this.movingDiv!.style.top = `${currentTop - (delta / 1000) * velocity}px`; // make sure to tweak the velocity, i like to convert the delta to seconds

    previousTime = now;
  }
发布评论

评论列表(0)

  1. 暂无评论