Javascript 从函数中生成的对象更改属性值

Javascript 从函数中生成的对象更改属性值,javascript,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,

我正在学习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 );
如果你能帮我解释一下哪条路最好,那么你就让我今晚过得很愉快:)
Cheers

您的对象
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);

我改变了您创建圆的方式,如下所示:

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 );