【发布时间】:2017-09-30 03:21:57
【问题描述】:
我正在从 API 中提取坐标并将它们设置为 Rectangle 类。循环遍历数据数组时,我可以创建每个矩形,但是在移动它们时,我遇到了麻烦。
x 坐标在 move() 的 setInterval 处在控制台中发生变化,但方块本身并没有在屏幕上移动。
当我在move() 中有c.clearRect(0,0,innerWidth, innerHeight); 时,所有矩形都会消失。没有它,它们根本不动。
if(this % 6 === 0){
c.fillStyle = "#000";
} else {
c.fillStyle = "" + this.color + "";
指的是数据数组,如果索引可以被 6 整除,则将该正方形设为黑色。尽管在这种情况下,它不起作用。
这是我的代码:
<script>
const canvas = document.getElementById("canvas");
const c = canvas.getContext('2d');
let xhReq = new XMLHttpRequest();
xhReq.open("GET", "(api here)", false);
xhReq.send(null);
const data = JSON.parse(xhReq.responseText);
class Rectangle {
constructor(x, y, w, h, vx, color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.vx = vx;
this.color = color;
}
draw() {
c.fillRect(this.x, this.y, this.w, this.h);
if(this % 6 === 0){
c.fillStyle = "#000";
} else {
c.fillStyle = "" + this.color + "";
}
}
move(){
c.clearRect(0,0,innerWidth, innerHeight);
if (this.x > 800 || this.x < 0){
this.vx = -this.vx;
}
this.x+= this.vx;
c.beginPath();
console.log("here is the x value:" + this.x);
}
}
for(let i=0; i<data.length; i++){
let info = data[i]
let rec = new Rectangle(info.x, info.y, info.w, info.h, info.vx, info.color);
rec.draw();
setInterval(function() {
rec.move();
}, 50);
}
</script>
【问题讨论】:
-
setInterval(function() { rec.move(); }, 50 * i);
-
不幸的是@MarouenMhiri 并没有改变任何东西
标签: javascript html canvas html5-canvas