在阵列js

时间:2015-06-02 04:52:38

标签: javascript canvas

之前没有真正使用array,我认为我在这里犯了一个错误 这段代码产生了第一个随机颜色/ vx等球,但没有其他球, 我不确定哪个部分不正确。

ball.x += ball.vx函数中animFrame()出现错误。

帮助?

var canvas;
var ctx;
var ball;
var numBalls = 5;

function Ball(radius, color) {
 this.x = 0;
 this.y = 0;
 this.vx = 0;
 this.vy = 0;
 this.radius = radius;
 this.color = random_color();
}

Ball.prototype.draw = function (ctx) {
  ctx.fillStyle = this.color;
  ctx.beginPath();
  ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI, true);
  ctx.closePath();
  ctx.fill();
}; 

function random_color() {

  var letter = "0123456789ABCDEF".split(""); 
  var color = "#";                           
  for(var i = 0; i < 6; i++){                
    color += letter[Math.round(Math.random()*15)]; 
  }
return color;
}


function init() {

  canvas = document.getElementById("gameCanvas");
  ctx = canvas.getContext("2d");
  balls = new Array();

for (var i = 0; i<numBalls; i++){
    ball = new Ball(Math.random() * 40 + 5, Math.random() * 0xffffff);
    ball.x = Math.random() * canvas.width / 2;
    ball.y = Math.random() * canvas.height / 2;
    ball.vx = Math.random() * 6 - 3;
    ball.vy = Math.random() * 6 - 3;
    ball.draw(ctx);
    balls.push(ball)
    animFrame();
}

function animFrame() {

    requestAnimationFrame(animFrame, canvas);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for(var i = 0; i < numBalls; i++){
        var ball = balls[i];
        ball.x += ball.vx;       // Undefined here down.
        ball.y += ball.vy;
        if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0)
            ball.vx = -ball.vx;
        if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0)
            ball.vy = -ball.vy;

        ball.draw(ctx);
    }
}

}

1 个答案:

答案 0 :(得分:1)

您的代码中存在很多语法错误,这就是它无法正常工作的原因:

  • 如果你从for循环中删除animframe()调用它会起作用,因为它只会推动一个球并停止for循环。

  • 您还在init()中定义了animframe()函数,将其移到外面。

  • 不要使用var balls = new Array(),只需使用var balls = [];在你的代码顶部。

下面:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}