Reputation: 105
I am learing JS and now making some stuff, now I got stuck on the following:
I made a function that draws a circle on the screen(in canvas), now I want to move it in x position. Only not sure how to do so. This is my code:
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 );
If you could help me out and explain what way is the best, then you made my evening :) Cheers
Upvotes: 1
Views: 50
Reputation: 7870
your object obj
is declared inside the function makeCircle(). if you want your code to work, you should declare it outside so as to make it accessible in update().
something like this should do the job:
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);
Upvotes: 1
Reputation: 12961
I have changed the way you create your circle like this:
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 );
Upvotes: 0