当用户单击确切位置时,如何创建粒子?

时间:2019-06-07 14:12:57

标签: javascript html canvas html5-canvas

我正在尝试使用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 个答案:

答案 0 :(得分:2)

您的粒子没有移动,因为您没有在requestAnimationFrame方法中再次调用draw。我会详细了解it does

还需要包括每个粒子移动的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 :(得分:1)

我对您的代码进行了一些更改。我为粒子创建了函数绘制和函数更新。创建新粒子时,您将赋予新位置。在创建带有循环的粒子时,这可以是随机的,也可以是您用鼠标单击的位置。另外,我还要添加一个功能来检测鼠标function oMousePos的位置。自从我在功能图上添加window.requestAnimationFrame(draw);以来,粒子一直在移动,但是由于粒子在一个方向上稳定移动,它们会消失。

您可以在鼠标按下时创建一个新粒子:

 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>