html--烟花3

news2024/9/23 17:22:27

html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas烟花粒子</title>
<meta name="keywords" content="canvas烟花"/>
<meta name="description" content="canvas动画/">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<canvas id="canvas">Canvas is not supported by your browser.</canvas>
<script src="js/index.js">
</script>
</body>
</html>

css

* { margin: 0; padding: 0; }

html, body { height: 100%; }

body {
  background: #000;
}

canvas {
  display: block;
  cursor: crosshair;
}

在这里插入图片描述

js


// Options
var options = {
  /* Which hue should be used for the first batch of rockets? */
  startingHue: 120,
  /* How many ticks the script should wait before a new firework gets spawned, if the user is holding down his mouse button. */
  clickLimiter: 5,
  /* How fast the rockets should automatically spawn, based on ticks */
  timerInterval: 40,
  /* Show pulsing circles marking the targets? */
  showTargets: true,
  /* Rocket movement options, should be self-explanatory */
  rocketSpeed: 2,
  rocketAcceleration: 1.03,
  /* Particle movement options, should be self-explanatory */
  particleFriction: 0.95,
  particleGravity: 1,
  /* Minimum and maximum amount of particle spawns per rocket */
  particleMinCount: 25,
  particleMaxCount: 40,
  /* Minimum and maximum radius of a particle */
  particleMinRadius: 3,
  particleMaxRadius: 5
};

// Local variables
var fireworks = [];
var particles = [];
var mouse = {down: false, x: 0, y: 0};
var currentHue = options.startingHue;
var clickLimiterTick = 0;
var timerTick = 0;
var cntRocketsLaunched = 0;

// Helper function for canvas animations
window.requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    function(cb) {
      window.setTimeout(callback, 1000 / 60);
    }
})();

// Helper function to return random numbers within a specified range
function random(min, max) {
  return Math.random() * (max - min) + min;
}

// Helper function to calculate the distance between 2 points
function calculateDistance(p1x, p1y, p2x, p2y) {
  var xDistance = p1x - p2x;
  var yDistance = p1y - p2y;
  return Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
}

// Setup some basic variables
var canvas = document.getElementById('canvas');
var canvasCtx = canvas.getContext('2d');
var canvasWidth = window.innerWidth;
var canvasHeight = window.innerHeight;

// Resize canvas
canvas.width = canvasWidth;
canvas.height = canvasHeight;

// Firework class
function Firework(sx, sy, tx, ty) {  
  // Set coordinates (x/y = actual, sx/sy = starting, tx/ty = target)
  this.x = this.sx = sx;
  this.y = this.sy = sy;
  this.tx = tx; this.ty = ty;
  
  // Calculate distance between starting and target point
  this.distanceToTarget = calculateDistance(sx, sy, tx, ty);
  this.distanceTraveled = 0;

  // To simulate a trail effect, the last few coordinates will be stored
  this.coordinates = [];
  this.coordinateCount = 3;
  
  // Populate coordinate array with initial data
  while(this.coordinateCount--) {
    this.coordinates.push([this.x, this.y]);
  }
  
  // Some settings, you can adjust them if you'd like to do so.
  this.angle = Math.atan2(ty - sy, tx - sx);
  this.speed = options.rocketSpeed;
  this.acceleration = options.rocketAcceleration;
  this.brightness = random(50, 80);
  this.hue = currentHue;
  this.targetRadius = 1;
  this.targetDirection = false;  // false = Radius is getting bigger, true = Radius is getting smaller
  
  // Increase the rockets launched counter
  cntRocketsLaunched++;
};

// This method should be called each frame to update the firework
Firework.prototype.update = function(index) {
  // Update the coordinates array
  this.coordinates.pop();
  this.coordinates.unshift([this.x, this.y]);
  
  // Cycle the target radius (used for the pulsing target circle)
  if(!this.targetDirection) {
    if(this.targetRadius < 8)
      this.targetRadius += 0.15;
    else
      this.targetDirection = true;  
  } else {
    if(this.targetRadius > 1)
      this.targetRadius -= 0.15;
    else
      this.targetDirection = false;
  }
  
  // Speed up the firework (could possibly travel faster than the speed of light) 
  this.speed *= this.acceleration;
  
  // Calculate the distance the firework has travelled so far (based on velocities)
  var vx = Math.cos(this.angle) * this.speed;
  var vy = Math.sin(this.angle) * this.speed;
  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 that's not the case, keep traveling.
  if(this.distanceTraveled >= this.distanceToTarget) {
    createParticles(this.tx, this.ty);
    fireworks.splice(index, 1);
  } else {
    this.x += vx;
    this.y += vy;
  }
};

// Draws the firework
Firework.prototype.draw = function() {
  var lastCoordinate = this.coordinates[this.coordinates.length - 1];
  
  // Draw the rocket
  canvasCtx.beginPath();
  canvasCtx.moveTo(lastCoordinate[0], lastCoordinate[1]);
  canvasCtx.lineTo(this.x, this.y);
  canvasCtx.strokeStyle = 'hsl(' + this.hue + ',100%,' + this.brightness + '%)';
  canvasCtx.stroke();
  
  // Draw the target (pulsing circle)
  if(options.showTargets) {
    canvasCtx.beginPath();
    canvasCtx.arc(this.tx, this.ty, this.targetRadius, 0, Math.PI * 2);
    canvasCtx.stroke();
  }
};

// Particle class
function Particle(x, y) {
  // Set the starting point
  this.x = x;
  this.y = y;
  
  // To simulate a trail effect, the last few coordinates will be stored
  this.coordinates = [];
  this.coordinateCount = 5;
  
  // Populate coordinate array with initial data
  while(this.coordinateCount--) {
    this.coordinates.push([this.x, this.y]);
  }
  
  // Set a random angle in all possible directions (radians)
  this.angle = random(0, Math.PI * 2);
  this.speed = random(1, 10);
  
  // Add some friction and gravity to the particle
  this.friction = options.particleFriction;
  this.gravity = options.particleGravity;
  
  // Change the hue to a random number
  this.hue = random(currentHue - 20, currentHue + 20);
  this.brightness = random(50, 80);
  this.alpha = 1;
  
  // Set how fast the particles decay
  this.decay = random(0.01, 0.03);
}

// Updates the particle, should be called each frame
Particle.prototype.update = function(index) {
  // Update the coordinates array
  this.coordinates.pop();
  this.coordinates.unshift([this.x, this.y]);
  
  // Slow it down (based on friction)
  this.speed *= this.friction;
  
  // Apply velocity to the particle
  this.x += Math.cos(this.angle) * this.speed;
  this.y += Math.sin(this.angle) * this.speed + this.gravity;
  
  // Fade out the particle, and remove it if alpha is low enough
  this.alpha -= this.decay;
  if(this.alpha <= this.decay) {
    particles.splice(index, 1);
  }
}

// Draws the particle
Particle.prototype.draw = function() {
  var lastCoordinate = this.coordinates[this.coordinates.length - 1];
  var radius = Math.round(random(options.particleMinRadius, options.particleMaxRadius));
  
  // Create a new shiny gradient
  var gradient = canvasCtx.createRadialGradient(this.x, this.y, 0, this.x, this.y, radius);
  gradient.addColorStop(0.0, 'white');
  gradient.addColorStop(0.1, 'white');
  gradient.addColorStop(0.1, 'hsla(' + this.hue + ',100%,' + this.brightness + '%,' + this.alpha + ')');
  gradient.addColorStop(1.0, 'black');
  
  // Draw the gradient
  canvasCtx.beginPath();
  canvasCtx.fillStyle = gradient;
  canvasCtx.arc(this.x, this.y, radius, Math.PI * 2, false);
  canvasCtx.fill();
}

// Create a bunch of particles at the given position
function createParticles(x, y) {
  var particleCount = Math.round(random(options.particleMinCount, options.particleMaxCount));
  while(particleCount--) {
    particles.push(new Particle(x, y));
  }
}

// Add an event listener to the window so we're able to react to size changes
window.addEventListener('resize', function(e) {
  canvas.width = canvasWidth = window.innerWidth;
  canvas.height = canvasHeight = window.innerHeight;
});

// Add event listeners to the canvas to handle mouse interactions
canvas.addEventListener('mousemove', function(e) {
  e.preventDefault();
  mouse.x = e.pageX - canvas.offsetLeft;
  mouse.y = e.pageY - canvas.offsetTop;
});

canvas.addEventListener('mousedown', function(e) {
  e.preventDefault();
  mouse.down = true;
});

canvas.addEventListener('mouseup', function(e) {
  e.preventDefault();
  mouse.down = false;
});

// Main application / script, called when the window is loaded
function gameLoop() {
  // This function will rund endlessly by using requestAnimationFrame (or fallback to setInterval)
  requestAnimFrame(gameLoop);
  
  // Increase the hue to get different colored fireworks over time
  currentHue += 0.5;
  
  // 'Clear' the canvas at a specific opacity, by using 'destination-out'. This will create a trailing effect.
  canvasCtx.globalCompositeOperation = 'destination-out';
  canvasCtx.fillStyle = 'rgba(0, 0, 0, 0.5)';
  canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
  canvasCtx.globalCompositeOperation = 'lighter';
  
  // Loop over all existing fireworks (they should be updated & drawn)
  var i = fireworks.length;
  while(i--) {
    fireworks[i].draw();
    fireworks[i].update(i);
  }
  
  // Loop over all existing particles (they should be updated & drawn)
  var i = particles.length;
  while(i--) {
    particles[i].draw();
    particles[i].update(i);
  }
  
  // Draw some text
  canvasCtx.fillStyle = 'white';
  canvasCtx.font = '14px Arial';
  canvasCtx.fillText('Rockets launched: ' + cntRocketsLaunched, 10, 24);
  
  // Launch fireworks automatically to random coordinates, if the user does not interact with the scene
  if(timerTick >= options.timerInterval) {
    if(!mouse.down) {
      fireworks.push(new Firework(canvasWidth / 2, canvasHeight, random(0, canvasWidth), random(0, canvasHeight / 2)));
      timerTick = 0;
    }
  } else {
    timerTick++;
  }
  
  // Limit the rate at which fireworks can be spawned by mouse
  if(clickLimiterTick >= options.clickLimiter) {
    if(mouse.down) {
      fireworks.push(new Firework(canvasWidth / 2, canvasHeight, mouse.x, mouse.y));
      clickLimiterTick = 0;
    }
  } else {
    clickLimiterTick++;
  }
}

window.onload = gameLoop();

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1596345.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

013_NaN_in_Matlab中的非数与调试方法

Matlab中的非数与调试方法 是什么&#xff1f; Matlab编程&#xff08;计算器使用&#xff09;中经常有个错误给你&#xff0c;这句话里可能包含一个关键词NaN。大部分学生都有过被 NaN 支配的痛苦记忆。 NaN 是 Not a Number 的缩写&#xff0c;表示不是一个数字。在 Matla…

00_STM32CubeMX如何新建一个工程

STM32CubeMX如何新建一个工程 STM32CubeMX如何新建一个工程以使用PA1口点亮LED为例子 STM32CubeMX如何新建一个工程 以使用PA1口点亮LED为例子 1.创建一个新工程 2.搜索芯片&#xff0c;然后双击 3.点击PA1引脚&#xff0c;设置为输出口 4.文件一定要保存到英文路径&#xff…

Normalizing Flows

需要学的是神经网络 f f f, 用于完成从source distribution (Pz)&#xff08;latent space&#xff0c;一般为高斯分布&#xff09;到 target distribution (Px) 的映射。 Normalizing Flows 是一种强大的生成模型&#xff0c;它通过学习一个可逆且易于计算的转换来将复杂的概…

Linux多进程开发2 - 进程间通信

1、进程间通信的概念 进程是一个独立的资源分配单元&#xff0c;不同进程之间的资源是独立的&#xff0c;没有关联&#xff0c;不能在一个进程中直接访问另一个进程的资源。但是&#xff0c;进程不是孤立的&#xff0c;不同的进程需要进行信息的交换和状态的传递等&…

【Datawhale LLM学习笔记】一、什么是大型语言模型(LLM)

文章目录 1. 什么是大模型2. 检索增强生成 RAG一、什么是 RAG二、RAG 的工作流程 3. langChain介绍一、什么是 LangChain二、LangChain 的核心组件 4. 开发 LLM 应用的整体流程一、何为大模型开发二、大模型开发的一般流程三、搭建 LLM 项目的流程简析&#xff08;以知识库助手…

明日周刊-第6期

最近一周杭州的天气起起伏伏&#xff0c;下雨就凉&#xff0c;不下雨就热。但是夏天的感觉确实是越来越浓烈了&#xff0c;又是一年夏&#xff0c;在这个夏天大家都有什么新的计划呢。 文章目录 一周热点资源分享言论歌曲推荐 一周热点 一、我国自主研发科技壮举震惊全球航天界…

SpringBoot删除菜品模块开发(SpringMVC分割参数、事务管理、异常处理、批量删除)

需求分析与设计 一&#xff1a;产品原型 在菜品列表页面&#xff0c;每个菜品后面对应的操作分别为修改、删除、停售&#xff0c;可通过删除功能完成对菜品及相关的数据进行删除。 删除菜品原型&#xff1a; 业务规则&#xff1a; 可以一次删除一个菜品&#xff0c;也可以批…

Zookeeper中的节点类型和实现持久化的两种方式

进入zookeeper的bin目录&#xff0c;执行./zkServer.sh start ../conf/zoo.cfg启动&#xff01; Zookeeper内部的数据模型 类似于数据结构中的树&#xff0c;同时也很像文件系统的目录&#xff0c; 节点的类型 持久节点&#xff1a;create /znode 创建出的节点&#xff0c…

如何在Linux系统部署Tale并实现无公网IP远程管理内网博客网站

文章目录 前言1. Tale网站搭建1.1 检查本地环境1.2 部署Tale个人博客系统1.3 启动Tale服务1.4 访问博客地址 2. Linux安装Cpolar内网穿透3. 创建Tale博客公网地址4. 使用公网地址访问Tale 前言 今天给大家带来一款基于 Java 语言的轻量级博客开源项目——Tale&#xff0c;Tale…

一本免费开源的电子书籍!这个 71.8k star 的项目,让你轻轻松松学会算法【文末有福利】

话说作为一名程序员&#xff0c;肯定都少不了在准备面试的时候刷 LeetCode 的算法题吧。虽然面试考察的算法题在工作中用到的非常少&#xff0c;但是确实是能让我们对常用的数据结构有更深刻的理解&#xff0c;以及对思维逻辑有很大的提升。不过枯燥的刷题可能让新手无从下手&a…

C++入门:类与对象(1)

本篇作为学习类与对象后的一些记录与感想&#xff0c;不适用于第一次接触类和对象的朋友。 目录 1.面向过程和面向对象 2.类 2.1类的基础知识 2.2 类中的访问限定符 2.3类中的函数声明定义分离&#xff08;如何在不同的文件中实现同一个类&#xff09; 2.4类的封装 2.5类…

Python+selenium的web自动化之元素的常用操作详解

前言 今天呢&#xff0c;笔者想和大家来聊聊pythonselenium的web自动化之元素的常用操作&#xff0c;废话不多说直接进入主题吧 一、常用操作 关键代码&#xff1a; 点击&#xff1a;ele.click()输入内容&#xff1a;ele.send_keys("内容")清空内容&#xff1a;el…

conda配置多版本python

安装conda 以下任选下载 Anaconda Miniconda 配置conda环境变量 比如windows&#xff0c;在配置我的电脑中的环境变量&#xff0c;在系统变量的Path中新增下面内容 需要根据实际目录进行更改 D:\soft\miniconda3 D:\soft\miniconda3\Scripts D:\soft\miniconda3\Library\bi…

嵌入式驱动学习第七周——GPIO子系统

前言 GPIO子系统是用来统一便捷地访问实现输入输出中断等效果。 嵌入式驱动学习专栏将详细记录博主学习驱动的详细过程&#xff0c;未来预计四个月将高强度更新本专栏&#xff0c;喜欢的可以关注本博主并订阅本专栏&#xff0c;一起讨论一起学习。现在关注就是老粉啦&#xff0…

云卓LS-01喊话器说明书-新版中文

一: 概述 LS-01 无人机喊话器适用于搭载无人机进行交通管制、现场指挥、应急救援、人群疏导、防疫宣传、景区安防、鱼塘巡视、林业防控等场景。产品具有喊话、警报、播放多媒体文件等多种功能。喊话器外壳采用尼龙加纤材质&#xff0c;具有抗、抗震、轻便灵活、外观新颖、质量稳…

NXopen C++ 装配体部件遍历 体积质量计算 NewMassProperties

打开装配体&#xff0c;逐一遍历部件测量体积&#xff0c;最后计算出装配体的总的体积和质量 NX1953VS2019 //1、模板文件添加头文件* #include <NXOpen/UnitCollection.hxx> #include <NXOpen/ScCollectorCollection.hxx> #include <NXOpen/Unit.hxx> #inc…

github 双因素验证

环境 华为手机 下载app 华为应用市场下载 输入对应验证码&#xff0c;然后一路下一步即可 联系方式 手机&#xff1a;13822161573 微信&#xff1a;txsolarterms QQ&#xff1a;419396409

实验一:配置IP地址

实验环境 主机A和主机B通过一根网线相连 需求描述 为两台主机配置IP地址&#xff0c;验证IP地址是否生效&#xff0c;验证同一网段的两台主机可以互通&#xff0c;不同网段的主机不能直接互通 一.实验拓扑 二.推荐步骤 1.为两台主机配置P地址&#xff0c;主机A为192.168.1.…

多无人机集群协同避障

matlab2020a正常运行 场景1规划结果 场景2规划结果 场景3规划结果 代码地址&#xff1a; 多无人机集群协同避障效果&#xff08;5架&#xff09;资源-CSDN文库

解决Ant Design Vue使用Modal对话框无法关闭的问题,本地可以关闭对话框但是打包后不能关闭对话框的问题。

首先说为什么会导致这个问题&#xff1a;因为现在vue官方的最新版本是3.4.x&#xff0c;可能是vue最新版本的部分代码与Ant Design不兼容导致的。 解决&#xff1a;所以将vue版本固定在vue3.4以下&#xff0c;就可以了。 1.删除node_modules和package-lock.json&#xff08;如…