html5 canvas跟随鼠标移动的彩色火焰动画特效

来源:https://www.sucaihuo.com/js/3891.html 2018-08-27 11:32浏览(902) 收藏

html5 canvas跟随鼠标移动的彩色火焰动画特效,酷炫的粒子火焰燃烧动画效果。
html5 canvas跟随鼠标移动的彩色火焰动画特效
分类:html5 > canvas 难易:初级
查看演示 下载资源 下载积分: 20 积分

js代码

<script>
window.onload = function(){
  
  var canvas = document.getElementById("canvas"),
      ctx = canvas.getContext("2d");
  
  var w = canvas.width = window.innerWidth * 2;
  var h = canvas.height = window.innerHeight * 2;

  var numParticles = 50,
      particles = [],
      radius = 12,
      speed = 0.1;

  function randomize(min, max) {
    return Math.round(Math.random() * (max - min) + min);
  };

  var pos = {
    x: w/2,
    y: h/2
  };

  var colors = ["#e67e22", "#e74c3c", "blue"];

  // clone object pos
  var accel = JSON.parse(JSON.stringify(pos));

  document.body.addEventListener("mousemove", function(e){
    pos.x = e.clientX;
    pos.y = e.clientY;
  });

  for(var i = 0; i < numParticles; i++){
    particles.push(new generate());
  };

  function generate(){
    this.x = pos.x;
    this.y = pos.y;
    this.radius = randomize(3,6);
    this.color = colors[Math.floor(Math.random() * colors.length)];
    this.vx = randomize(-2, 2);
    this.vy = randomize(5, 10);
    this.life = randomize(20, 30);
  };

  render();

  function render(){
    ctx.clearRect(0, 0, w, h);

    accel.x += (pos.x - accel.x) * 0.15;
    accel.y += (pos.y - accel.y) * 0.15;

    ctx.beginPath();
    ctx.fillStyle = "#f1c40f";
    ctx.arc(accel.x, accel.y, radius, 0, Math.PI * 2, false);
    ctx.fill();
    ctx.globalCompositeOperation = "xor";

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

      ctx.beginPath();
      ctx.fillStyle = p.color;
      ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2, false);
      ctx.fill();

      p.x += p.vx;
      p.y -= p.vy;

      p.radius -= 0.075;
      p.life--;

      if(p.life < 0 || p.radius < 0){
        particles[j] = new generate();
      }

    }

    requestAnimationFrame(render);
  }

  // credit
  balapaCop("Elastic Fire", "rgba(255,255,255,.5)");
  
}
</script>
评论0
头像

系统已开启自动识别垃圾评论机制,识别到的自动封号,下载出错或者资源有问题请联系全栈客服QQ 1915635791

1 2