javascript - 将鼠标移动添加到 Canvas 动画

标签 javascript animation html5-canvas mouseevent

我已经在canvas html中制作了一个动画,但现在我想让球的原点根据我的鼠标位置在 Canvas 上移动。我想添加鼠标事件功能,但我似乎无法弄清楚逻辑并将其添加到代码中,任何帮助将不胜感激!

function runParticles () {
  var canvas = document.createElement("canvas");
  c = canvas.getContext("2d");
  var particles = {};
  var particleIndex = 0;
  var particleNum = 15;

  // set canvas size
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  // add canvas to body
  document.body.appendChild(canvas);

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

  function Particle() {
  this.x = canvas.width / 2;
  this.y = canvas.height / 2;
  this.vx = Math.random() * 10 - 5;
  this.vy = Math.random() * 10 - 5;
  this.gravity = 0.3;
  particleIndex++;
  particles[particleIndex] = this;
  this.id = particleIndex;
  this.life = 0;


  this.maxLife = Math.random() * 30 + 60;


  this.color = "hsla(" + parseInt(Math.random() * 360, 10) + ",90%,60%,0.5";
  }

  Particle.prototype.draw = function() {
  this.x += this.vx;
  this.y += this.vy;


  if (Math.random() < 0.1) {
      this.vx = Math.random() * 10 - 5;
      this.vy = Math.random() * 10 - 5;
  }

  this.life++;
  if (this.life >= this.maxLife) {
      delete particles[this.id];
  }

  c.fillStyle = this.color;
  //c.fillRect(this.x, this.y, 5, 10);
  c.beginPath();
  c.arc(this.x, this.y, 2.5, degToRad(0), degToRad(360));
  c.fill();
  };

  setInterval(function() {
  //normal setting before drawing over canvas w/ black background
  c.globalCompositeOperation = "source-over";
  c.fillStyle = "rgba(0,0,0,0.5)";
  c.fillRect(0, 0, canvas.width, canvas.height);
  for (var i = 0; i < particleNum; i++) {
      new Particle();
  }

  // c.globalCompositeOperation = "darken";

  for (var i in particles) {
      particles[i].draw();
  }
  }, 30);
}

function degToRad(deg) {
            var radians = (deg * Math.PI / 180) - Math.PI / 2;
            return radians;
        }
<!DOCTYPE html5>
<html>

<head>
  <title>disturbed</title>

  <script src="toto.js" type="text/javascript"></script>
  <script>
    window.onload = () => runParticles();
  </script>
</head>

<body>
</body>

</html>

最佳答案

  1. 我添加了一个检测鼠标位置的函数:
function oMousePos(canvas, evt) {
  var ClientRect = canvas.getBoundingClientRect();
    return { //objeto
    x: Math.round(evt.clientX - ClientRect.left),
    y: Math.round(evt.clientY - ClientRect.top)
  }
}
  • 我声明了一个变量 m(鼠标)。
  • var m = {x:canvas.width/2,y:canvas.height/2};
    

    我已经改变了粒子的起源 this.x = canvas.width/2; this.y = canvas.height/2; 到 this.x = m.x; this.y = m.y;

    这是鼠标不在 Canvas 上移动时的位置

  • 我添加了一个事件“mousemove”。当鼠标在 Canvas 上移动时,其位置会发生变化。
  • canvas.addEventListener("mousemove", (evt)=>{
      m = oMousePos(canvas, evt);
    })
    

    我还添加了一个事件“mouseleave”。当鼠标离开 Canvas 时,鼠标回到中心。

    canvas.addEventListener("mouseleave", (evt)=>{
      m = {x:canvas.width/2,y:canvas.height/2};
    })
    
  • 此外,我还更改了 requestAnimationFrame 的 setInterval (更加高效)。里面的代码就是你的代码。
  • function runParticles () {
      var canvas = document.createElement("canvas");
      c = canvas.getContext("2d");
      var particles = {};
      var particleIndex = 0;
      var particleNum = 8;
    
      // set canvas size
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
      
      var m = {x:canvas.width/2,y:canvas.height/2};///////
    
      // add canvas to body
      document.body.appendChild(canvas);
    
      // style the canvas
      c.fillStyle = "black";
      c.fillRect(0, 0, canvas.width, canvas.height);
    
      function Particle() {
      this.x = m.x;//////////
      this.y = m.y;//////////
      this.vx = Math.random() * 10 - 5;
      this.vy = Math.random() * 10 - 5;
      this.gravity = 0.3;
      particleIndex++;
      particles[particleIndex] = this;
      this.id = particleIndex;
      this.life = 0;
    
    
      this.maxLife = Math.random() * 30 + 60;
    
    
      this.color = "hsla(" + parseInt(Math.random() * 360, 10) + ",90%,60%,0.5";
      }
    
      Particle.prototype.draw = function() {
      this.x += this.vx;
      this.y += this.vy;
    
    
      if (Math.random() < 0.1) {
          this.vx = Math.random() * 10 - 5;
          this.vy = Math.random() * 10 - 5;
      }
    
      this.life++;
      if (this.life >= this.maxLife) {
          delete particles[this.id];
      }
    
      c.fillStyle = this.color;
      //c.fillRect(this.x, this.y, 5, 10);
      c.beginPath();
      c.arc(this.x, this.y, 2.5, degToRad(0), degToRad(360));
      c.fill();
      };
      
    function Draw() {
      window.requestAnimationFrame(Draw);
      c.globalCompositeOperation = "source-over";
      c.fillStyle = "rgba(0,0,0,0.5)";
      c.fillRect(0, 0, canvas.width, canvas.height);
      for (var i = 0; i < particleNum; i++) {
          new Particle();
      }
    
      // c.globalCompositeOperation = "darken";
    
      for (var i in particles) {
          particles[i].draw();
      } 
      }
      
      Draw();
      
      
    ///////////////////
    canvas.addEventListener("mousemove", (evt)=>{
      m = oMousePos(canvas, evt);
    })
    canvas.addEventListener("mouseleave", (evt)=>{
      m = {x:canvas.width/2,y:canvas.height/2};
    })
    ///////////////////
       
    }
    
    function degToRad(deg) {
                var radians = (deg * Math.PI / 180) - Math.PI / 2;
                return radians;
            }
    
    
    runParticles();
    
    
    
    
    function oMousePos(canvas, evt) {
      var ClientRect = canvas.getBoundingClientRect();
    	return { //objeto
    	x: Math.round(evt.clientX - ClientRect.left),
    	y: Math.round(evt.clientY - ClientRect.top)
      }
    }
    body,canvas{margin:0;padding:0;}

    我希望这会有所帮助。

    关于javascript - 将鼠标移动添加到 Canvas 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52481111/

    相关文章:

    iOS菜单标题到导航栏标题动画

    javascript - 如何保护js免受自定义事件的影响

    javascript - 检查事件目标是否为超链接

    javascript - Windows Phone Internet Explorer Mobile 7 浏览器是否支持触摸事件?

    javascript - 向 DOM 添加文本时为什么要使用变量?

    javascript - 鼠标滚动卡住 chrome 选项卡

    javascript - 显示 block 与。不透明度

    javascript - 当您除了过渡状态之外还预定义了 css 状态时,Angular 动画无法正常运行

    javascript - 在 Android 浏览器中将图像渲染为数据流

    javascript - PHP+JS : How to do Fileuploads in HTML Form as Content-Type Multipart (via JS)?