Canvas: X Value Changing In Console But Not In Canvas
Solution 1:
There are a lot of issues with your code.
You are only updating the position and not making the draw call again. Move the
rec.draw()
call inside yoursetInterval
. Remember, ordering is important. Ideally, you shouldupdate()
first anddraw()
later.setInterval(function() { rec.move(); rec.draw(); }, 50);
Also, remove these lines from the
move()
function as you don't want to clear the canvas every time you update the variables. Clear the canvas in the beginning of thedraw()
function. Plus, since you're dealing withfillRect()
, you dont need to includebeginPath()
c.clearRect(0,0,innerWidth, innerHeight); ... c.beginPath();
You first need to specify the
fillStyle
then proceed with drawing the rectangle usingfillRect()
, not the other way round. Thedraw()
function should look like this:draw() { c.clearRect(0, 0, innerWidth, innerHeight); if(this % 6 === 0){ // <-- Not really sure what is going on here c.fillStyle = "#000"; } else { c.fillStyle = "" + this.color + ""; } c.fillRect(this.x, this.y, this.w, this.h); }
In the code block in point number #3 you are using the Modulus Operator
%
on the the instance of the class itself i.e.this
and not a number. I'm assuming you want something likethis.x
in there.
Apart from the points above there are still a handful of issues with your code. But it's outside the context of this question.
Edited for a final solution below:
const canvas = document.getElementById("canvas");
const context = canvas.getContext('2d');
const xhr = new XMLHttpRequest();
// Usng var as we are making an async request and need to update this variablevardata = null;
// An empty array to store our rectanglesvar collection = [];
// Using an asyn request as we don't necessarily need to wait for this step
xhr.open('GET', '<api>', true)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
data = JSON.parse(xhr.responseText);
dataLoaded();
} else {
// The request gave an error response
}
}
};
xhr.send();
function dataLoaded(){
for(let i = 0; i < data.length; i++){
let info = data[i];
collection.push(new Rectangle(info.x, info.y, info.w, info.h, info.vx, info.color));
}
setInterval(animate, 50);
}
function animate(){
context.clearRect(0, 0, canvas.width, canvas.height);
for(let i = 0; i < collection.length; i++){
let rect = collection[i];
rect.update();
rect.draw();
}
}
classRectangle{
constructor(x, y, w, h, vx, color){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.vx = vx;
this.color = color;
}
update(){
if (this.x > 800 || this.x < 0){
this.vx = -this.vx;
}
this.x += this.vx;
}
draw(){
context.fillStyle = this.color;
context.fillRect(this.x, this.y, this.w, this.h);
}
}
Post a Comment for "Canvas: X Value Changing In Console But Not In Canvas"