javascript - 为什么“Circle”类看不到我发送给他的参数?
问题描述
请告诉我为什么,当我将坐标转移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 调用中:)
推荐阅读
- video - 我怎样才能解复用/重新复用视频流 h264?
- json - 如何使用 jquery 从linkedin API 获取数据
- triggers - 板条箱数据库触发器实现
- azure-api-management - API 管理 [Client to API] 客户端认证
- node.js - redis rsmq worker 无法从 redis 队列中获取消息
- xcode - Xcode 9 添加本地化时无法打开 Info.plist
- amazon-web-services - 无法执行 HTTP 请求以使用 Postman 在 Cognito AWS 中注册新用户
- math - 如何计算括号顺序的所有可能组合
- javascript - 反应json获取价值
- android - 就性能而言,我应该使用哪些布局?