Как я могу создать частицу, когда пользователь нажимает на точное место? - PullRequest
3 голосов
/ 07 июня 2019

Я пытаюсь создать частицы с помощью Javascript и HTML5 Canvas, и я хотел бы, чтобы canvas был неэффективным, а это означает, что когда пользователь нажимает на конкретную область страницы, он порождает частицу со случайной скоростью, размером и цветом,Затем эта частица будет перемещаться по всему экрану и продолжать подпрыгивать, пока пользователь не обновит страницу.

С наилучшими пожеланиями, 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 ]

2 голосов
/ 07 июня 2019

Ваша частица не движется, потому что вы не вызываете requestAnimationFrame снова в методе draw. Я бы прочитал больше о том, что это делает .

Вам также необходимо указать направление X и Y, в котором движется каждая частица. Это потому, что каждая частица имеет свое собственное направление и не должна разделять направления.

Для частиц, появляющихся при нажатии, просто добавьте событие mousedown к canvas и захватите координаты. Затем вставьте новый Particle в ваш массив, чтобы draw работал с ними.

Вы также можете контролировать начальное направление, используя 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>
1 голос
/ 07 июня 2019

Я сделал несколько изменений в вашем коде. Я создал функцию рисования и обновление функции для частиц. При создании новой частицы вы даете новую позицию. Это может быть случайным при создании частиц с петлей, или это может быть место, где вы щелкнули мышью. Также я добавляю функцию для определения положения мыши function oMousePos. Теперь частицы движутся с тех пор, как я добавил window.requestAnimationFrame(draw); к функции рисования, но поскольку частицы неуклонно движутся в одном направлении, они исчезнут.

Вы можете создать новую частицу в mousedown:

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

Надеюсь, это поможет.

// 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...