热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

canvas烟花特效锦集分享!

canvas可以实现不同动画效果,本文主要记录几种不同节日烟花效果实现。 实现一htmlcssbody{background:#

canvas可以实现不同动画效果,本文主要记录几种不同节日烟花效果实现。

canvas烟花特效锦集 

实现一

canvas烟花特效锦集

html

  

css

  body {      background: #000;      margin: 0;  }    canvas {      cursor: crosshair;      display: block;  }  

js

  // when animating on canvas, it is best to use requestAnimationFrame instead of setTimeout or setInterval  // not supported in all browsers though and sometimes needs a prefix, so we need a shim  window.requestAnimFrame = (function () {      return window.requestAnimationFrame ||          window.webkitRequestAnimationFrame ||          window.mozRequestAnimationFrame ||          function (callback) {              window.setTimeout(callback, 1000 / 60);          };  })();    // now we will setup our basic variables for the demo  var canvas = document.getElementById('canvas'),      ctx = canvas.getContext('2d'),      // full screen dimensions      cw = window.innerWidth,      ch = window.innerHeight,      // firework collection      fireworks = [],      // particle collection      particles = [],      // starting hue      hue = 120,      // when launching fireworks with a click, too many get launched at once without a limiter, one launch per 5 loop ticks      limiterTotal = 5,      limiterTick = 0,      // this will time the auto launches of fireworks, one launch per 80 loop ticks      timerTotal = 80,      timerTick = 0,      mousedown = false,      // mouse x coordinate,      mx,      // mouse y coordinate      my;    // set canvas dimensions  canvas.width = cw;  canvas.height = ch;    // now we are going to setup our function placeholders for the entire demo    // get a random number within a range  function random(min, max) {      return Math.random() * (max - min) + min;  }    // calculate the distance between two points  function calculateDistance(p1x, p1y, p2x, p2y) {      var xDistance = p1x - p2x,          yDistance = p1y - p2y;      return Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2));  }    // create firework  function Firework(sx, sy, tx, ty) {      // actual coordinates      this.x = sx;      this.y = sy;      // starting coordinates      this.sx = sx;      this.sy = sy;      // target coordinates      this.tx = tx;      this.ty = ty;      // distance from starting point to target      this.distanceToTarget = calculateDistance(sx, sy, tx, ty);      this.distanceTraveled = 0;      // track the past coordinates of each firework to create a trail effect, increase the coordinate count to create more prominent trails      this.coordinates = [];      this.coordinateCount = 3;      // populate initial coordinate collection with the current coordinates      while (this.coordinateCount--) {          this.coordinates.push([this.x, this.y]);      }      this.angle = Math.atan2(ty - sy, tx - sx);      this.speed = 2;      this.acceleration = 1.05;      this.brightness = random(50, 70);      // circle target indicator radius      this.targetRadius = 1;  }    // update firework  Firework.prototype.update = function (index) {      // remove last item in coordinates array      this.coordinates.pop();      // add current coordinates to the start of the array      this.coordinates.unshift([this.x, this.y]);        // cycle the circle target indicator radius      if (this.targetRadius <8) {          this.targetRadius += 0.3;      } else {          this.targetRadius = 1;      }        // speed up the firework      this.speed *= this.acceleration;        // get the current velocities based on angle and speed      var vx = Math.cos(this.angle) * this.speed,          vy = Math.sin(this.angle) * this.speed;      // how far will the firework have traveled with velocities applied?      this.distanceTraveled = calculateDistance(this.sx, this.sy, this.x + vx, this.y + vy);        // if the distance traveled, including velocities, is greater than the initial distance to the target, then the target has been reached      if (this.distanceTraveled >= this.distanceToTarget) {          createParticles(this.tx, this.ty);          // remove the firework, use the index passed into the update function to determine which to remove          fireworks.splice(index, 1);      } else {          // target not reached, keep traveling          this.x += vx;          this.y += vy;      }  }    // draw firework  Firework.prototype.draw = function () {      ctx.beginPath();      // move to the last tracked coordinate in the set, then draw a line to the current x and y      ctx.moveTo(this.coordinates[this.coordinates.length - 1][0], this.coordinates[this.coordinates.length - 1][          1      ]);      ctx.lineTo(this.x, this.y);      ctx.strokeStyle = 'hsl(' + hue + ', 100%, ' + this.brightness + '%)';      ctx.stroke();        ctx.beginPath();      // draw the target for this firework with a pulsing circle      ctx.arc(this.tx, this.ty, this.targetRadius, 0, Math.PI * 2);      ctx.stroke();  }    // create particle  function Particle(x, y) {      this.x = x;      this.y = y;      // track the past coordinates of each particle to create a trail effect, increase the coordinate count to create more prominent trails      this.coordinates = [];      this.coordinateCount = 5;      while (this.coordinateCount--) {          this.coordinates.push([this.x, this.y]);      }      // set a random angle in all possible directions, in radians      this.angle = random(0, Math.PI * 2);      this.speed = random(1, 10);      // friction will slow the particle down      this.friction = 0.95;      // gravity will be applied and pull the particle down      this.gravity = 1;      // set the hue to a random number +-20 of the overall hue variable      this.hue = random(hue - 20, hue + 20);      this.brightness = random(50, 80);      this.alpha = 1;      // set how fast the particle fades out      this.decay = random(0.015, 0.03);  }    // update particle  Particle.prototype.update = function (index) {      // remove last item in coordinates array      this.coordinates.pop();      // add current coordinates to the start of the array      this.coordinates.unshift([this.x, this.y]);      // slow down the particle      this.speed *= this.friction;      // apply velocity      this.x += Math.cos(this.angle) * this.speed;      this.y += Math.sin(this.angle) * this.speed + this.gravity;      // fade out the particle      this.alpha -= this.decay;        // remove the particle once the alpha is low enough, based on the passed in index      if (this.alpha <= this.decay) {          particles.splice(index, 1);      }  }         // draw particle  Particle.prototype.draw = function () {        ctx.beginPath();      // move to the last tracked coordinates in the set, then draw a line to the current x and y      ctx.moveTo(this.coordinates[this.coordinates.length - 1][0], this.coordinates[this.coordinates.length - 1][          1      ]);      ctx.lineTo(this.x, this.y);      ctx.strokeStyle = 'hsla(' + this.hue + ', 100%, ' + this.brightness + '%, ' + this.alpha + ')';      ctx.stroke();    }    // create particle group/explosion  function createParticles(x, y) {      // increase the particle count for a bigger explosion, beware of the canvas performance hit with the increased particles though      var particleCount = 30;      while (particleCount--) {          particles.push(new Particle(x, y));      }  }    // main demo loop  function loop() {      // this function will run endlessly with requestAnimationFrame      requestAnimFrame(loop);        // increase the hue to get different colored fireworks over time      hue += 0.5;        // normally, clearRect() would be used to clear the canvas      // we want to create a trailing effect though      // setting the composite operation to destination-out will allow us to clear the canvas at a specific opacity, rather than wiping it entirely      ctx.globalCompositeOperation = 'destination-out';      // decrease the alpha property to create more prominent trails      ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';      ctx.fillRect(0, 0, cw, ch);      // change the composite operation back to our main mode      // lighter creates bright highlight points as the fireworks and particles overlap each other      ctx.globalCompositeOperation = 'lighter';        var text = "HAPPY NEW YEAR !";      ctx.fOnt= "50px sans-serif";      var textData = ctx.measureText(text);      ctx.fillStyle = "rgba(" + parseInt(random(0, 255)) + "," + parseInt(random(0, 255)) + "," + parseInt(random(0,          255)) + ",0.3)";      ctx.fillText(text, cw / 2 - textData.width / 2, ch / 2);        // loop over each firework, draw it, update it      var i = fireworks.length;      while (i--) {          fireworks[i].draw();          fireworks[i].update(i);      }        // loop over each particle, draw it, update it      var i = particles.length;      while (i--) {          particles[i].draw();          particles[i].update(i);      }        // launch fireworks automatically to random coordinates, when the mouse isn't down      if (timerTick >= timerTotal) {          if (!mousedown) {              // start the firework at the bottom middle of the screen, then set the random target coordinates, the random y coordinates will be set within the range of the top half of the screen                for (var h = 0; h <50; h++) {                  fireworks.push(new Firework(cw / 2, ch / 2, random(0, cw), random(0, ch)));              }                timerTick = 0;          }      } else {          timerTick++;      }        // limit the rate at which fireworks get launched when mouse is down      if (limiterTick >= limiterTotal) {          if (mousedown) {              // start the firework at the bottom middle of the screen, then set the current mouse coordinates as the target              fireworks.push(new Firework(cw / 2, ch / 2, mx, my));              limiterTick = 0;          }      } else {          limiterTick++;      }  }    // mouse event bindings  // update the mouse coordinates on mousemove  canvas.addEventListener('mousemove', function (e) {      mx = e.pageX - canvas.offsetLeft;      my = e.pageY - canvas.offsetTop;  });    // toggle mousedown state and prevent canvas from being selected  canvas.addEventListener('mousedown', function (e) {      e.preventDefault();      mousedown = true;  });    canvas.addEventListener('mouseup', function (e) {      e.preventDefault();      mousedown = false;  });    // once the window loads, we are ready for some fireworks!  window.Onload= loop;    

实现二

canvas烟花特效锦集

html

    2018

  • 1
  • 2
  • 3
  • 4

推荐阅读
  • 本文详细解析了使用C++实现的键盘输入记录程序的源代码,该程序在Windows应用程序开发中具有很高的实用价值。键盘记录功能不仅在远程控制软件中广泛应用,还为开发者提供了强大的调试和监控工具。通过具体实例,本文深入探讨了C++键盘记录程序的设计与实现,适合需要相关技术的开发者参考。 ... [详细]
  • 在PHP中如何正确调用JavaScript变量及定义PHP变量的方法详解 ... [详细]
  • 本指南介绍了如何在ASP.NET Web应用程序中利用C#和JavaScript实现基于指纹识别的登录系统。通过集成指纹识别技术,用户无需输入传统的登录ID即可完成身份验证,从而提升用户体验和安全性。我们将详细探讨如何配置和部署这一功能,确保系统的稳定性和可靠性。 ... [详细]
  • Python 程序转换为 EXE 文件:详细解析 .py 脚本打包成独立可执行文件的方法与技巧
    在开发了几个简单的爬虫 Python 程序后,我决定将其封装成独立的可执行文件以便于分发和使用。为了实现这一目标,首先需要解决的是如何将 Python 脚本转换为 EXE 文件。在这个过程中,我选择了 Qt 作为 GUI 框架,因为之前对此并不熟悉,希望通过这个项目进一步学习和掌握 Qt 的基本用法。本文将详细介绍从 .py 脚本到 EXE 文件的整个过程,包括所需工具、具体步骤以及常见问题的解决方案。 ... [详细]
  • POJ 2482 星空中的星星:利用线段树与扫描线算法解决
    在《POJ 2482 星空中的星星》问题中,通过运用线段树和扫描线算法,可以高效地解决星星在窗口内的计数问题。该方法不仅能够快速处理大规模数据,还能确保时间复杂度的最优性,适用于各种复杂的星空模拟场景。 ... [详细]
  • importpymysql#一、直接连接mysql数据库'''coonpymysql.connect(host'192.168.*.*',u ... [详细]
  • 本文详细介绍了 PHP 中对象的生命周期、内存管理和魔术方法的使用,包括对象的自动销毁、析构函数的作用以及各种魔术方法的具体应用场景。 ... [详细]
  • 在Delphi7下要制作系统托盘,只能制作一个比较简单的系统托盘,因为ShellAPI文件定义的TNotifyIconData结构体是比较早的版本。定义如下:1234 ... [详细]
  • 利用REM实现移动端布局的高效适配技巧
    在移动设备上实现高效布局适配时,使用rem单位已成为一种流行且有效的技术。本文将分享过去一年中使用rem进行布局适配的经验和心得。rem作为一种相对单位,能够根据根元素的字体大小动态调整,从而确保不同屏幕尺寸下的布局一致性。通过合理设置根元素的字体大小,开发者可以轻松实现响应式设计,提高用户体验。此外,文章还将探讨一些常见的问题和解决方案,帮助开发者更好地掌握这一技术。 ... [详细]
  • DVWA学习笔记系列:深入理解CSRF攻击机制
    DVWA学习笔记系列:深入理解CSRF攻击机制 ... [详细]
  • 本文探讨了在PHP中实现MySQL分页查询功能的优化方法与实际应用。通过详细分析分页查询的常见问题,提出了多种优化策略,包括使用索引、减少查询字段、合理设置缓存等。文章还提供了一个具体的示例,展示了如何通过优化模型加载和分页参数设置,显著提升查询性能和用户体验。 ... [详细]
  • 在分析和解决 Keepalived VIP 漂移故障的过程中,我们发现主备节点配置如下:主节点 IP 为 172.16.30.31,备份节点 IP 为 172.16.30.32,虚拟 IP 为 172.16.30.10。故障表现为监控系统显示 Keepalived 主节点状态异常,导致 VIP 漂移到备份节点。通过详细检查配置文件和日志,我们发现主节点上的 Keepalived 进程未能正常运行,最终通过优化配置和重启服务解决了该问题。此外,我们还增加了健康检查机制,以提高系统的稳定性和可靠性。 ... [详细]
  • 本文介绍了如何利用Struts1框架构建一个简易的四则运算计算器。通过采用DispatchAction来处理不同类型的计算请求,并使用动态Form来优化开发流程,确保代码的简洁性和可维护性。同时,系统提供了用户友好的错误提示,以增强用户体验。 ... [详细]
  • C++ 异步编程中获取线程执行结果的方法与技巧及其在前端开发中的应用探讨
    本文探讨了C++异步编程中获取线程执行结果的方法与技巧,并深入分析了这些技术在前端开发中的应用。通过对比不同的异步编程模型,本文详细介绍了如何高效地处理多线程任务,确保程序的稳定性和性能。同时,文章还结合实际案例,展示了这些方法在前端异步编程中的具体实现和优化策略。 ... [详细]
  • PHP预处理常量详解:如何定义与使用常量 ... [详细]
author-avatar
mobiledu2502891413
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有