html--烟花3

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 pointthis.distanceToTarget = calculateDistance(sx, sy, tx, ty);this.distanceTraveled = 0;// To simulate a trail effect, the last few coordinates will be storedthis.coordinates = [];this.coordinateCount = 3;// Populate coordinate array with initial datawhile(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 countercntRocketsLaunched++;
};// This method should be called each frame to update the firework
Firework.prototype.update = function(index) {// Update the coordinates arraythis.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;elsethis.targetDirection = true;  } else {if(this.targetRadius > 1)this.targetRadius -= 0.15;elsethis.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 rocketcanvasCtx.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 pointthis.x = x;this.y = y;// To simulate a trail effect, the last few coordinates will be storedthis.coordinates = [];this.coordinateCount = 5;// Populate coordinate array with initial datawhile(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 particlethis.friction = options.particleFriction;this.gravity = options.particleGravity;// Change the hue to a random numberthis.hue = random(currentHue - 20, currentHue + 20);this.brightness = random(50, 80);this.alpha = 1;// Set how fast the particles decaythis.decay = random(0.01, 0.03);
}// Updates the particle, should be called each frame
Particle.prototype.update = function(index) {// Update the coordinates arraythis.coordinates.pop();this.coordinates.unshift([this.x, this.y]);// Slow it down (based on friction)this.speed *= this.friction;// Apply velocity to the particlethis.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 enoughthis.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 gradientvar 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 gradientcanvasCtx.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 timecurrentHue += 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 textcanvasCtx.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 sceneif(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 mouseif(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.hqwc.cn/news/619838.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

亚马逊卖家如何选择合适的海外仓系统,如何利用海外仓系统进行退货换标?

在亚马逊的全球电商舞台上&#xff0c;如何选择一个合适的海外仓系统&#xff0c;高效管理海外仓库、优化退货换标流程&#xff0c;成为了卖家们亟待解决的问题。 今天&#xff0c;让我们就来聊聊怎么挑选海外仓系统&#xff0c;还有怎么利用它来处理退货换标的。 一、选择海外…

web3项目自动连接小狐狸以及小狐狸中的各种“地址”详解

刚做web3的时候&#xff0c;比较迷糊的就是人们口中说的各种地址&#xff0c;小狐狸钱包地址&#xff0c;私钥地址&#xff0c;跳转地址&#xff0c;接口地址&#xff0c;交易地址&#xff0c;等等XX地址&#xff0c;常常感觉跟做链的同事们说话不在一个频道。 这一小节&#x…

Java开发从入门到精通(十一):Java常用的API编程接口:ArrayList集合

Java大数据开发和安全开发 &#xff08;一&#xff09;Java的常用API:ArrayList集合1.1 什么是集合?1.2 有数组&#xff0c;为啥还学习集合?1.3 ArrayList集合该怎么学呢?1.3.1 创建ArrayList对象1.3.ArrayList的增删改查操作1.3.3 ArrayList集合的案例 &#xff08;一&…

波纹加载---

代码&#xff1a; <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Document</title><style…

【C语言】指针篇-初识指针(1/5)

&#x1f308;个人主页&#xff1a;是店小二呀 &#x1f308;C语言笔记专栏&#xff1a;C语言笔记 &#x1f308;C笔记专栏&#xff1a; C笔记 &#x1f308;喜欢的诗句:无人扶我青云志 我自踏雪至山巅 文章目录 **内存和地址(知识铺垫(了解即可))**如何理解编址**指针变量*…

【unity】【C#】游戏音乐播放和发布

今天我们来认识一下有关 unity 音乐的一些知识 我们先创建 AudioClips 文件夹&#xff0c;这个文件夹通常就是 unity 中存放音乐的文件夹&#xff0c;然后拖进音乐文件进去 这里为大家提供了两个音乐&#xff0c;有需要可以自取 百度网盘&#xff1a;https://pan.baidu.com/s…

泛域名/通配符SSL证书有免费的吗?怎么申请?

我们需要明确的是&#xff0c;市场上确实存在免费的泛域名SSL证书&#xff0c;但这些免费证书通常由自动化的证书颁发机构&#xff08;CA&#xff09;提供&#xff0c;如JoySSL、Lets Encrypt。这些免费证书虽然能够满足基本的加密需求&#xff0c;但在服务支持、保险额度、信任…

Python7种运算符及运算符优先级

🥇作者简介:CSDN内容合伙人、新星计划第三季Python赛道Top1 🔥本文已收录于Python系列专栏: 零基础学Python 💬订阅专栏后可私信博主进入Python学习交流群,进群可领取Python视频教程以及Python相关电子书合集 私信未回可以加V:hacker0327 备注零基础学Python 订阅专…

Rust - 所有权

所有的程序都必须和计算机内存打交道&#xff0c;如何从内存中申请空间来存放程序的运行内容&#xff0c;如何在不需要的时候释放这些空间&#xff0c;成了重中之重&#xff0c;也是所有编程语言设计的难点之一。在计算机语言不断演变过程中&#xff0c;出现了三种流派&#xf…

医疗大模型,巨头们的新赛场

配图来自Canva可画 说起近两年最热门的话题&#xff0c;那一定非大模型莫属了。众所周知&#xff0c;伴随着ChatGPT的强势出圈&#xff0c;全球范围内掀起了一波人工智能热潮&#xff0c;国内外的诸多企业都开足马力&#xff0c;推出了自己的大模型产品。而AI大模型产品的不断…

基于Vue的低代码可拔插自定义组件

背景说明 在低代码初期&#xff0c;各个厂商的前端低代码搭建框架基本集中在JQuery、Vue、React 等。但在低代码的实施阶段&#xff0c;对于前端的展示&#xff0c;都遇到了同一个挑战&#xff1a;部分场景下需要根据自身业务来定制表单组件&#xff08;如表单组件UI和业务逻辑…

虚拟机下CentOS7开启SSH连接

虚拟机下CentOS7开启SSH连接 自己在VMware中装了CentOS 6.3&#xff0c;然后主机&#xff08;或者说xshell&#xff09;与里面的虚拟机连不通&#xff0c;刚学习&#xff0c;一头雾水&#xff0c;查了半天&#xff0c;也不知道怎么弄。 在虚拟机&#xff08;Vmware Workstatio…