gpt4 book ai didi

javascript - 为什么 "Circle"类看不到我发送给他的参数?

转载 作者:行者123 更新时间:2023-12-03 01:34:22 25 4
gpt4 key购买 nike

请告诉我为什么当我将坐标options传递给类Circle时,他看不到它们?

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

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

  • x - x 坐标的初始值
  • y - y 坐标的初始值
  • 直径 - 宽度和高度的值
  • 颜色 - 填充颜色

方法: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});

最佳答案

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

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

在你的_update调用中:)

关于javascript - 为什么 "Circle"类看不到我发送给他的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51142777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com