peter flanagan peter flanagan - 3 months ago 17
Javascript Question

drawing squares on canvas in foor loop only drawing one square

I am using the canvas element to draw white squares on a black canvas background.

I am having no difficulties drawing a black background, and can draw one star, however I am having difficulties drawing more than one white square. I am confused as I am drawing a new white star on each loop however, for some reason it is not drawing each star (white square).

Based on this article I believe my code should work.

Please see code below:

function Starfield () {
this.ctx = document.getElementById('canvas');
this.ctx = this.ctx.getContext("2d");
this.stars = 2;
this.createCanvas();
this.createStar();
}

Starfield.prototype.createCanvas = function() {
this.ctx.fillStyle = "#000";
this.ctx.fillRect(0,0, window.innerHeight, window.innerWidth );
};

Starfield.prototype.createStar = function() {
var rand1 = Math.random() * 50;
var rand2 = Math.random() * 50;
for (var i = 0; i < this.stars; i++) {
this.ctx.fillStyle = "#fff";
this.ctx.fillRect(rand1, rand2, 2, 2);
};
};

Answer

Try the below:

Starfield.prototype.createStar = function() {
    for (var i = 0; i < this.stars; i++) {
        var rand1 = Math.random() * 50;
        var rand2 = Math.random() * 50;
        this.ctx.fillStyle = "#fff";
        this.ctx.fillRect(rand1, rand2, 2, 2);
    };
};

I moved the calls to Math.random() inside the loop. Your code was choosing just one location and drawing all the stars at that same location (on top of each other). You need a different random location for each star.

Comments