How can I create a particle when the user clicks on the exact spot?

Viewed 57

I am tryng to create particles with Javascript and HTML5 Canvas, and I would like canvas to be itneractive, which means that when the user clicks on a specfic area of a page then it spawns a particle at random velocity, size and colour. This particle will then bouce all over the screen and keep on bouncing until the user refreshes the page.

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 < 5; 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, false);
    c.fill();

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

// Drawing the particle
window.requestAnimationFrame(draw);
<canvas id="canvas" width="1024" height="768">Your browser does not support HTML5 Canvas.</canvas>

2 Answers

Your particle is not moving because you are not calling requestAnimationFrame again in the draw method. I would read more about what it does.

You also need to include the X and Y direction that each particle is moving. This is because each particle has it's own direction and should not share directions.

For the particles appearing when you click, just add a mousedown event to the canvas and capture the coordinates. Then push a new Particle into your array to have draw work with them.

You can also control the beginning direction by using Math.random().

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

var dist = 5;

// Creation of an array of particles
var particles = [];

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

  // Randomizing the position on the canvas
  this.posX = x;
  this.posY = y;
  
  // Use Math.random() to set a random direction to start with.
  var ran = Math.random();
  if (ran < .5) {
    this.dirX = -1; // Include the X direction this particle is moving
  } else {
    this.dirX = 1; // Include the X direction this particle is moving
  }
  
  ran = Math.random();
  if (ran < .5) {
    this.dirY = -1; // Include the X direction this particle is moving
  } else {
    this.dirY = 1; // Include the X direction this particle is moving
  }
}


canvas.addEventListener("mousedown", function(event) {
  var x = event.x - canvas.offsetLeft;
  var y = event.y - canvas.offsetTop;
  particles.push(new Particle(x, y));
});


// 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, false);
    c.fill();
    
    p.posX += p.dirX * dist; // Move X
    p.posY += p.dirY * dist; // Move Y
    
    // Incrementing the X and Y postition
    if (p.dirX == 1 && p.posX + dist > canvas.width) { // Moving right and reached the end
        p.posX -= p.posX + dist - canvas.width;
        p.dirX *= -1 // Reverse direction
    } else if (p.dirX == -1 && p.posX < 0) { // Moving left and reached the end
        p.posX = 0;
        p.dirX *= -1; // Reverse direction
    }
    
    if (p.dirY == 1 && p.posY + dist > canvas.height) { // Moving down and reached the end
        p.posY -= p.posY + dist - canvas.height;
        p.dirY *= -1 // Reverse direction
    } else if (p.dirY == -1 && p.posY < 0) { // Moving up and reached the end
        p.posY = 0;
        p.dirY *= -1; // Reverse direction
    }  
  };
  window.requestAnimationFrame(draw); // Call me aagain recursively 
}

// Drawing the particle
window.requestAnimationFrame(draw);
<canvas id="canvas">Your browser does not support HTML5 Canvas.</canvas>

I've made a few changes to your code. I've created a function draw and a function update for the particles. When creating a new particle you give the new position. This can be a random one when creating the particles with a loop, or it can be the spot where you clicked with the mouse. Also I'm adding a function to detect the position of the mouse function oMousePos. Now the particles are moving since I've added window.requestAnimationFrame(draw); to the function draw, but since the particles are moving steadily in one direction they will disappear.

You can create a new particle on mousedown:

 canvas.addEventListener("mousedown",(e)=>{
      let m = oMousePos(canvas, e);//the position of the mouse 
      particles.push(new Particle(m))
    })

I hope it helps.

// 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";
var posX = canvas.width/2,
    posY = canvas.height/2;
// Creation of an array of particles
var particles = [];


// Creation of a fucntion which will help us create multiple particles
function Particle(pos) {
  
  this.posX = pos.x;
  this.posY = pos.y;
}

Particle.prototype.draw = function(){ 
    c.beginPath();
    c.fillStyle = "white";
    c.arc(this.posX, this.posY, 5, 0, Math.PI * 2, false);
    c.fill();
}
Particle.prototype.update = function(){ 
   this.posX++;
   this.posY++;
}


for (var i = 0; i < 5; i++) {
  let pos = {}
  // Randomizing the position on the canvas
  pos.x = Math.random() * canvas.width;
  pos.y = Math.random() * canvas.height;
  particles.push(new Particle(pos));
  
}

// Creating a draw function
function draw() {
  window.requestAnimationFrame(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
    p.update();
    p.draw()
    

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

// Drawing the particle
window.requestAnimationFrame(draw);


canvas.addEventListener("mousedown",(e)=>{
  let m = oMousePos(canvas, e)
  particles.push(new Particle(m))
})

function oMousePos(canvas, evt) {
  var ClientRect = canvas.getBoundingClientRect();
 return { //objeto
 x: Math.round(evt.clientX - ClientRect.left),
 y: Math.round(evt.clientY - ClientRect.top)
}
}
<canvas id="canvas" width="1024" height="768">Your browser does not support HTML5 Canvas.</canvas>

Related