一个烟花小程序
<html><head>
<meta charset=utf-8>
<style>
body {
background: #000;
margin: 0;
}
canvas {
cursor: crosshair;
display: block;
}
</style>
</head>
<body>
<canvas id=0></canvas>
</body>
<script>
$=function(b){return document.getElementById(b)};
// 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
requestAnimFrame = ( function() {
return requestAnimationFrame || webkitRequestAnimationFrame || mozRequestAnimationFrame ||
function( callback ) {
window.setTimeout( callback, 1000 / 60 );
};
})();
// now we will setup our basic variables for the demo
var canvas = $(0),
ctx = canvas.getContext( '2d' ),
// full screen dimensions
cw = window.innerWidth,
ch = window.innerHeight,
// 烟花集合
fireworks = [],
// 粒子集合
particles = [],
// 起始色调
色调 = 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 coordinate,
mp;
// 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( p1, p2 ) {
var xDistance = p1[0] - p2[0],
yDistance = p1[1] - p2[1];
return Math.sqrt( Math.pow( xDistance, 2 ) + Math.pow( yDistance, 2 ) );
}
// create 烟花
function 烟花( 起点, 目标点 ) {
// actual 坐标集合
this.点 = 起点;
// starting 坐标集合
this.起点 = 起点;
// target 坐标集合
this.目标点 = 目标点;
// distance from starting point to target
this.distanceToTarget = calculateDistance( 起点, 目标点 );
this.distanceTraveled = 0;
// track the past 坐标集合 of each 烟花 to create a trail effect, increase the coordinate count to create more prominent trails
this.坐标集合 = [];
this.coordinateCount = 3;
// populate initial coordinate collection with the current 坐标集合
while( this.coordinateCount-- ) {
this.坐标集合.push( 起点 );
}
this.angle = Math.atan2( 目标点[1] - 起点[1], 目标点[0] - 起点[0] );
this.速度 = 2;
this.加速度 = 1.05;
this.亮度 = random( 50, 70 );
// circle target indicator radius
this.targetRadius = 1;
}
// update 烟花
烟花.prototype.update = function( index ) {
// remove last item in 坐标集合 array
this.坐标集合.pop();
// add current 坐标集合 to the start of the array
this.坐标集合.unshift( this.点 );
// cycle the circle target indicator radius
if( this.targetRadius < 8 ) {
this.targetRadius += 0.3;
} else {
this.targetRadius = 1;
}
// 速度 up the 烟花
this.速度 *= this.加速度;
// get the current velocities based on angle and 速度
var vx = Math.cos( this.angle ) * this.速度,
vy = Math.sin( this.angle ) * this.速度;
// how far will the 烟花 have traveled with velocities applied?
this.distanceTraveled = calculateDistance( this.起点, [this.点[0] + vx, this.点[1] + 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.目标点 );
// remove the 烟花, use the index passed into the update function to determine which to remove
fireworks.splice( index, 1 );
} else {
// target not reached, keep traveling
this.点=[this.点[0]+vx,this.点[1]+vy];
}
}
// 画 烟花
烟花.prototype.画 = function() {
ctx.beginPath();
// move to the last tracked coordinate in the set, then 画 a line to the current point
ctx.moveTo( this.坐标集合[ this.坐标集合.length - 1][ 0 ], this.坐标集合[ this.坐标集合.length - 1][ 1 ] );
ctx.lineTo( this.点[0], this.点[1] );
ctx.strokeStyle = 'hsl(' + 色调 + ', 100%, ' + this.亮度 + '%)';
ctx.stroke();
ctx.beginPath();
// 画 the target for this 烟花 with a pulsing circle
ctx.arc( this.目标点[0], this.目标点[1], this.targetRadius, 0, Math.PI * 2 );
ctx.stroke();
}
// create particle
function Particle( 点 ) {
this.点 = 点;
// track the past 坐标集合 of each particle to create a trail effect, increase the coordinate count to create more prominent trails
this.坐标集合 = [];
this.coordinateCount = 5;
while( this.coordinateCount-- ) {
this.坐标集合.push( 点 );
}
// set a random angle in all possible directions, in radians
this.angle = random( 0, Math.PI * 2 );
this.速度 = random( 1, 10 );
// friction will slow the particle down
this.friction = 0.95;
// 重力加速度 will be applied and pull the particle down
this.重力加速度 = 1;
// set the 色调 to a random number +-20 of the overall 色调 variable
this.色调 = random( 色调 - 20, 色调 + 20 );
this.亮度 = 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 坐标集合 array
this.坐标集合.pop();
// add current 坐标集合 to the start of the array
this.坐标集合.unshift( this.点 );
// slow down the particle
this.速度 *= this.friction;
// apply velocity
this.点=[this.点[0]+Math.cos( this.angle ) * this.速度,this.点[1]+Math.sin( this.angle ) * this.速度 + this.重力加速度];
// 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 );
}
}
// 画 particle
Particle.prototype.画 = function() {
ctx. beginPath();
// move to the last tracked 坐标集合 in the set, then 画 a line to the current point
ctx.moveTo( this.坐标集合[ this.坐标集合.length - 1 ][ 0 ], this.坐标集合[ this.坐标集合.length - 1 ][ 1 ] );
ctx.lineTo( this.点[0], this.点[1] );
ctx.strokeStyle = 'hsla(' + this.色调 + ', 100%, ' + this.亮度 + '%, ' + this.alpha + ')';
ctx.stroke();
}
// create particle group/explosion
function createParticles( 点 ) {
// 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( 点 ) );
}
}
// main demo loop
function loop() {
requestAnimFrame( loop );
// increase the 色调 to get different colored fireworks over time
色调 += 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';
// loop over each 烟花, 画 it, update it
var i = fireworks.length;
while( i-- ) {
fireworks[ i ].画();
fireworks[ i ].update( i );
}
// loop over each particle, 画 it, update it
var i = particles.length;
while( i-- ) {
particles[ i ].画();
particles[ i ].update( i );
}
// launch fireworks automatically to random 坐标集合, when the mouse isn't down
if( timerTick >= timerTotal ) {
if( !mousedown ) {
// start the 烟花 at the bottom middle of the screen, then set the random target 坐标集合, the random y 坐标集合 will be set within the range of the top half of the screen
fireworks.push( new 烟花( [cw / 2, ch], [random( 0, cw ), random( 0, ch / 2 )] ) );
timerTick = 0;
}
} else {
timerTick++;
}
// limit the rate at which fireworks get launched when mouse is down
if( limiterTick >= limiterTotal ) {
if( mousedown ) {
// start the 烟花 at the bottom middle of the screen, then set the current mouse 坐标集合 as the target
fireworks.push( new 烟花( [cw / 2, ch], mp ) );
limiterTick = 0;
}
} else {
limiterTick++;
}
}
// mouse event bindings
// update the mouse 坐标集合 on mousemove
canvas.addEventListener( 'mousemove', function( e ) {
mp = [e.pageX - canvas.offsetLeft, 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;
</script>
</html>