更改函数中对象的属性值

时间:2013-12-25 20:06:18

标签: javascript

我正在学习JS并且正在制作一些东西,现在我遇到了以下问题:

我制作了一个在屏幕上绘制圆圈的功能(在画布中),现在我想将它移动到x位置。只是不知道该怎么做。这是我的代码:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var FPS = 35;

function makeCircle(x, y, radius, vx, vy) {
  var obj = {
    x : x,
    y : y,
    radius : radius,
    vx : vx,
    vy : vy,
    draw: function() {
        ctx.beginPath();
        ctx.arc( this.x, this.y, this.radius, 0, 2 * Math.PI );
        ctx.fillStyle = this.color;
        ctx.fill();
    }
};
  obj.draw();
  return obj;
}


function draw() {
     ctx.clearRect( 0, 0, canvas.width, canvas.height );

     makeCircle(100, 100, 35, 60, 60);
}

function update() {
    obj.x += obj.vx;
}
function tick() {
  draw();
  update();
}

setInterval( tick, 1000 / FPS );

如果你可以帮我解释一下最好的方法,那你就是我的晚上:) 干杯

2 个答案:

答案 0 :(得分:1)

您的对象obj在函数makeCircle()中声明。如果你想让你的代码工作,你应该在外面声明它,以便在update()中访问它。

这样的事情应该可以胜任:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var FPS = 35;

var obj = {
    init: function(x, y, radius, vx, vy) {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.vx = vx;
        this.vy = vy;
    },

    draw: function() {
    context.clearRect( 0, 0, canvas.width, canvas.height );
        context.beginPath();
        context.arc( this.x, this.y, this.radius, 0, 2 * Math.PI );
        context.fillStyle = this.color;
        context.fill();
    },

    update: function() {
        this.x += this.vx
    }
};

function tick() {
  obj.draw();
  obj.update();
}


obj.init(100, 100, 35, 60, 60);

setInterval( tick, 1000 / FPS);

答案 1 :(得分:0)

我改变了你创建圈子的方式:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var FPS = 35;

var Circle = function Circle(x, y, radius, vx, vy) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.vx = vx;
    this.vy = vy;
    this.draw = function () {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
        ctx.fillStyle = this.color;
        ctx.fill();
    };
    this.update = function update() {
        this.x += this.vx;
    };
}

Circle.getInstance = function Circle$getInstance() {
    var circle = new Circle();
    circle.draw();
    circle.update();
    return circle;
}

setInterval( Circle.getInstance, 1000 / FPS );