user11611159
user11611159

Reputation:

Why cannot I display particles on the webpage?

I am trying to display particles on my screen, and then animate them in a way. Like just moving around and boucing on the screen. I cannot find the error which does not allow me to display these particles.

Best regards, Tar2ed

// Initializing the canvas
var canvas = document.getElementById("canvas");
var c = canvas.getContext('2d');

// Setting the positition in the middle of the canvas
var posX = 512,
  posY = 384;

// Creation of an array of particles
var particles = [];
for (var i = 0; i < 50; i++) {
  particles.push(new Particle());
}

// Creation of a fucntion which will help us create multiple particles
function Particle() {

  // Randomizing the position on the canvas
  this.posX = Math.random() * canvas.width;
  this.posY = Math.random() * canvas.height;
}

// Creating a draw function
function draw() {

  // Painting the canvas in black
  c.fillStyle = "black";
  c.fillRect(0, 0, canvas.width, canvas.height);

  for (var d = 0; d < Particle.length; d++) {
    var p = particles[d];

    // Creating the particle
    c.beginPath();
    c.fillStyle = "white";
    c.arc(p.posX, p.posY, 5, Math.PI * 2, false);
    c.fill();

    // Incrementing the X and Y postition
    p.posX++;
    p.posY++;
  };
}

// Drawing the particle
setInterval(draw, 33);
<canvas id="canvas"></canvas>

Upvotes: 2

Views: 42

Answers (1)

Jan
Jan

Reputation: 2853

  1. In the for-loop: Particle.length should be particles.length.
  2. The arguments for c.arc are wrong. They should be: c.arc(p.posX, p.posY, 5, 0, Math.PI * 2);
  3. You should consider utilizing window​.request​Animation​Frame() for calling the draw-loop.

Demo from your example:

// Initializing the canvas
var canvas = document.getElementById("canvas");
var c = canvas.getContext('2d');

// Setting the positition in the middle of the canvas
var posX = 512,
    posY = 384;

// Creation of an array of particles
var particles = [];
for (var i = 0; i < 50; i++ ){
  particles.push(new Particle());
}

// Creation of a fucntion which will help us create multiple particles
function Particle() {

  // Randomizing the position on the canvas
  this.posX = Math.random() * canvas.width;
  this.posY = Math.random() * canvas.height;
}

// Creating a draw function
function draw() {

  // Painting the canvas in black
  c.fillStyle = "black";
  c.fillRect(0, 0, canvas.width, canvas.height);

  for (var d = 0; d < particles.length; d++) {
    var p = particles[d];

    // Creating the particle
    c.beginPath();
    c.fillStyle = "white";
    c.arc(p.posX, p.posY, 5, 0, Math.PI * 2);
    c.fill();

    // Incrementing the X and Y postition
    p.posX++;
    p.posY++;
  }
}

// Drawing the particle
setInterval(draw, 33);
<canvas id="canvas" width="310" height="160">

Upvotes: 2

Related Questions