首页 > 解决方案 > 为什么物体不移动到坐标?

问题描述

我实现了一个具有属性的 Circle 类:

方法:draw()- 在屏幕上绘制由指定属性描述的元素。

方法:move({x = 0, y = 0})- 沿向量 (x, y) 移动绘制的对象 - 每个时间段 (100ms) 根据 x 和 y 的值改变(加\减)坐标。

以及内部方法update(),它用对象的颜色、x、y 的相应值来改变绘制圆的位置。

告诉我为什么我的圆圈不会在给定的坐标处以 1 秒的间隔移动?

class Circle {
    constructor(options) {
        this.x = options.x;
        this.y = options.y;
        this.diameter = options.diameter;
        this.color = options.color;
    }

    draw() {
        let div = document.createElement('div');
        div.style.position = 'absolute';
        div.style.left = `${this.x}px`;
        div.style.top = `${this.y}px`;
        div.style.width = `${this.diameter}px`;
        div.style.height = `${this.diameter}px`;
        div.style.border = "1px solid;";
        div.style.borderRadius = "50%";
        div.style.backgroundColor = `${this.color}`;
        document.body.appendChild(div);
    }

    move({x = 0, y = 0}) {
        let circle = document.getElementsByTagName('div')[0];
        setInterval(function moved() {
            circle.style.left = circle.offsetLeft + x + "px";
            circle.style.top = circle.offsetTop + y + "px";
        }, 1000)
    }
    _update() {
        this.x = x.move;
        this.y = y.move;
    }
}
let options = {
    x: 100,
    y: 100,
    diameter: 100,
    color: 'red'
};
let circle = new Circle(options);
circle.draw();
circle.move({x: 200, y: 200});

标签: javascriptoopecmascript-6

解决方案


这是一个初始示例(如果我得到了你想要的),你可以用它来得到你想要的。

快速概述:

  • 用户设置圆实例所需的坐标
  • 可以通过将duration选项传递给move(...)方法来更改动画的持续时间,例如move({x: 100, y: 100, duration: 2500})
  • 圆圈将开始一个代码setInterval以重新定位圆圈
  • 实际,中间xy坐标将根据给定的进度计算duration
  • 当动画结束时,xy坐标将被设置为最初给定的坐标,move(...)并且圆的整个移动完成

笔记:

  • 我知道你没有要求动画,但我敢假设,这种演示会更有效地帮助你理解和/或得到你的结果。
  • 我提取了您的代码部分,您在其中设置圆的位置以遵守DRY原则。
  • 为了使代码更易于演示,我将坐标降低到较低的值,但它也适用于较大的值
  • 出于某种原因,许多人认为在现代浏览器中使用动画制作任何东西都是一种不好的做法。如果您想要一种获得更好动画的方法,请阅读该功能。我在这里使用,因为动画不是这个问题的主要主题setIntervalwindow.requestAnimationFrame()setInterval

class Circle {
  constructor(options) {
    Object.assign(this, 
      // the default options of the Circle constructor
      {      
        x: 10,
        y: 10,
        diameter: 50,
        color: 'red'
      }, 
      // the options, that were passed and will be used to override the default options
      options
    );
  
    // the circle's move/update animation interval in ms (similar to FPS in games)
    this.updateInterval = 100;
  }

  draw() {
    const div = document.createElement('div');
    div.style.position = 'absolute';
    div.style.width = `${this.diameter}px`;
    div.style.height = `${this.diameter}px`;
    div.style.border = "1px solid;";
    div.style.borderRadius = "50%";
    div.style.backgroundColor = `${this.color}`;
    document.body.appendChild(div);
    // store the reference to the div element for later use
    this.circle = div;
    // use the refacterd positioning function
    this._reposition();
  }

  move({x = 0, y = 0, duration = 1000}) {
    // store coordinates to use, when the circle will be moved
    this.initialX = this.x;
    this.initialY = this.y;
    this.destX = x,
    this.destY = y;
    
    // store the current time in ms
    this.startTime = Date.now();
    this.duration = duration
    
    // if a previous setInterval of this circle instance is still running, clear it (stop it)
    clearInterval(this.intervalId);
    // start the update (tick/ticker in games)
    this.intervalId = setInterval(this._update.bind(this), this.updateInterval);
  }
  
  _update() {
    // calculate the elapsed time
    const elapsed = Date.now() - this.startTime;    
    // calculate the progress according to the total given duration in percent
    let progress = elapsed / this.duration;
    // bound to [n..1]
    if (progress > 1) {
      progress = 1;
    }
    
    // set the x and y coordinates according to the progress...
    this.x = this.initialX + (this.destX * progress);
    this.y = this.initialY + (this.destY * progress);
    // ...and reposition the circle    
    this._reposition();
    console.log('update', this.x, this.y, progress);
    
    // stop the update, when the end is reached
    if (elapsed >= this.duration) {
      console.log('stopped', this.x, this.y, progress);
      clearInterval(this.intervalId);
    }
  }
  
  _reposition() {
    // set the position of the circle instance
    this.circle.style.left = `${this.x}px`;
    this.circle.style.top = `${this.y}px`;
  }
}

const options = {
  x: 10,
  y: 10,
  diameter: 50,
  color: 'red'
};

const circle = new Circle(options);
circle.draw();
circle.move({x: 300, y: 50});


推荐阅读