首页 > 解决方案 > 为什么“Circle”类看不到我发送给他的参数?

问题描述

请告诉我为什么,当我将坐标转移options到班级Circle时,他看不到它们?

我想实现逻辑,当圆遇到屏幕的任何边缘时,它会跳回来(通过符号将对应向量坐标的值更改为相反的值并move()用新向量调用方法)

关于我的代码逻辑的一点点: 我实现了一个带有属性的 Circle 类:

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

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

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

class Circle {
    constructor(options) {
        this.x = options.x;
        this.y = options.y;
        this.diameter = options.diameter;
        this.color = options.color;
// the circle's move/update animation interval in ms
    }

    draw() {
        const 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);
        // store the reference to the div element for later use
        this.circle = div;
        // use the refacterd positioning function
        this._reposition();
    }

    setColor(newColor) {
        return this.color = newColor;
    }

    move({x = 0, y = 0, duration = 1000}) {
        this.updateInterval = 100;
        this.direction = 1;
        this.destX = 0,
            this.destY = 4;
        // 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
        window.requestAnimationFrame(this._update.bind(this));
    }

    _update() {
        // set the x and y coordinates according to the progress
        let newX = this.x + this.direction * this.destX;
        let newY = this.y + this.direction * this.destY;
        if (newY >= window.innerHeight - this.diameter) {
            this.direction = -1;
        } else if (newY <= 0) {
            this.direction = 1;
        }
        if (newX >= window.innerWidth - this.diameter) {
            this.direction = -1;
        } else if (newX <= 0) {
            this.direction = 1;
        }
        this.x = newX;
        this.y = newY;

        this._reposition();
        window.requestAnimationFrame(this._update.bind(this));
    }

    _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: 100,
    y: 100,
    diameter: 100,
    color: 'red'
};
const circle = new Circle(options);
circle.draw();
circle.setColor("green");
circle.move({x: 1235, y:0});

标签: javascript

解决方案


您的 _update 方法永远不会重置颜色,请尝试

 this.circle.style.backgroundColor = `${this.color}`;

在你的 _update 调用中:)


推荐阅读