Reputation: 497
I am trying to move the arcs along the x-axis, but it's giving an error that x is not defined in the update function. Are the variables not properly placed or some reference is missing??
Code
<canvas id="myCanvas"></canvas>
<script>
var myCanvas = document.getElementById("myCanvas");
var c = myCanvas.getContext("2d");
var redArc = new Circle(50, 60, 10, "red");
var greenArc = new Circle(80, 60, 15, "green");
var blueArc = new Circle(120, 60, 20, "blue");
function Circle(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
c.fillStyle = this.color;
c.fill();
}
this.update = function() {
redArc.x += 1;
greenArc.x += 1;
blueArc.x += 1;
this.draw();
}
this.update();
}
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, myCanvas.clientWidth, myCanvas.clientHeight);
redArc.update();
greenArc.update();
blueArc.update();
}
animate();
How do I go about fixing it? Any suggestions Thanks!!
Upvotes: 0
Views: 1496
Reputation: 32879
Replace your update
method with the following :
this.update = function() {
this.x += 1;
this.draw();
}
you should be using this.x
, not the variable names.
var myCanvas = document.getElementById("myCanvas");
var c = myCanvas.getContext("2d");
var redArc = new Circle(50, 60, 10, "red");
var greenArc = new Circle(80, 60, 15, "green");
var blueArc = new Circle(120, 60, 20, "blue");
function Circle(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
c.fillStyle = this.color;
c.fill();
}
this.update = function() {
this.x += 1;
this.draw();
}
this.update();
}
function animate() {
c.clearRect(0, 0, myCanvas.clientWidth, myCanvas.clientHeight);
redArc.update();
greenArc.update();
blueArc.update();
requestAnimationFrame(animate);
}
animate();
<canvas id="myCanvas"></canvas>
Upvotes: 2