每次运行此代码时,我都会得到不同的结果,这是怎么回事
I have different results every time i run this code, how come?
我正在编写的代码应该让10个不同颜色的球从墙上弹下来,但当我运行代码时,我会不断得到一个或两个不同颜色球,否则它每1/10次就会完美工作一次。有什么想法吗?画布动画
<body>
<canvas id = "canvas" width="600" height = "500"> </canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = 300 //changes canvas size
var height = 400
width = canvas.width
height = canvas.height
/* In this constructor, the starting position
of the ball is set to this.x and this.y
*/
var Ball = function () {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.xSpeed = -2; // -2 means 2 pixels left for every step of animation.
this.ySpeed = 3;
var circle = function (x, y, radius, color, fill) { //function to make drawing circles faster
ctx.strokeStyle = color
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2, false);
if (fill === true) {
ctx.fillStyle = color;
ctx.fill()
}
ctx.stroke();
}
// The Ball maker
x = Math.floor(Math.random() * 10)
myColors = ["Green", "Red", "Orange", "Yellow", "Chocolate", "Brown", "Silver", "Black", "Purple", "Blue"]
Ball.prototype.draw = function () {
circle(this.x, this.y, 3, myColors[x], true)
};
// this will move the balls
Ball.prototype.move = function () {
this.x += this.xSpeed;
this.y += this.ySpeed;
};
Ball.prototype.checkCollision = function () { //makes the balls bounce off walls
if (this.x < 0 || this.x > width) {
this.xSpeed = -this.xSpeed;
}
if (this.y < 0 || this.y > height) {
this.ySpeed = -this.ySpeed;
}
}
}
var moBalls = [] //stores balls to be called later
for (var x = 0; x < 10; x++) {
moBalls[x] = new Ball()
}
width = canvas.width
height = canvas.height
setInterval(function () {
ctx.clearRect(0, 0, width, height);
for (x = 0; x < 10; x++) { //takes the balls from moBalls and moves the ten of them
moBalls[x].draw()
moBalls[x].move()
moBalls[x].checkCollision();
}
ctx.lineWidth = 4
ctx.strokeRect(0, 0, width, height); //makes the walls
}, 30);
</script>
</body>
</html>
我很确定这是因为您在多个位置使用变量x
,而不使用var
关键字(正如@pointy所说,您没有声明它)。
使用var x
生成从数组中选择颜色的随机数,也可以在for
循环中调用draw
方法。
或者更好的是,使用不同的变量名称,这些名称可以清楚地表明变量的意图。例如:
var randomColorIndex = Math.floor(Math.random() * 10)
var myColors = ["Green", "...", "Blue"]
Ball.prototype.draw = function () {
circle(this.x, this.y, 3, myColors[randomColorIndex], true)
};
(我知道这似乎有点长,但这只是一个例子;使用对你来说最重要的东西)。
相关文章:
- Javascript袖珍参考,第121页:这是怎么回事;猴子补丁”;方法应该有效
- 基本的HTML Javascript程序.这是怎么回事
- 每次运行此代码时,我都会得到不同的结果,这是怎么回事
- jQuery extend 函数是怎么回事
- {} + [] 和 [] + {} 结果怎么会不同
- “Bada” - 这个JavaScript片段是怎么回事
- 如何使文本字段为空?这是怎么回事
- 自定义SVG签名在CODEPEN上有效,但在本地机器上无效-这是怎么回事
- 事件侦听器不会在IE中被调用 - 这是怎么回事
- HTML 中的空脚本标签是怎么回事
- 这个JavaScript片段是怎么回事
- 调用堆栈超出,甚至没有任何递归.这是怎么回事
- 带有奇怪输出的单行 - 字符串作为“这个”是怎么回事
- 这个速记运算符是怎么回事
- 网站似乎在没有向服务器发送密码的情况下登录用户;这是怎么回事
- 将多个值分配给一个变量.这是怎么回事
- 图片库的图片预装器?这是怎么回事
- 这个CSS渲染阻塞是怎么回事
- Javascript中的回调真的是方法调用吗?如果是的话,他们是怎么回事'级联'
- 有人能解释一下这部分是怎么回事吗