HTML5全屏烟花动画特效

html代码:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Canvas全屏烟花动画特效</title><style>
/* basic styles for black background and crosshair cursor */
body {background: #000;margin: 0;
}canvas {cursor: crosshair;display: block;
}
</style></head>
<body><canvas id="canvas"></canvas><script>
// 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 dimensionscw = window.innerWidth,ch = window.innerHeight,// firework collectionfireworks = [],// particle collectionparticles = [],// starting huehue = 120,// when launching fireworks with a click, too many get launched at once without a limiter, one launch per 5 loop tickslimiterTotal = 5,limiterTick = 0,// this will time the auto launches of fireworks, one launch per 80 loop tickstimerTotal = 80,timerTick = 0,mousedown = false,// mouse x coordinate,mx,// mouse y coordinatemy;// 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 coordinatesthis.x = sx;this.y = sy;// starting coordinatesthis.sx = sx;this.sy = sy;// target coordinatesthis.tx = tx;this.ty = ty;// distance from starting point to targetthis.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 trailsthis.coordinates = [];this.coordinateCount = 3;// populate initial coordinate collection with the current coordinateswhile( 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 radiusthis.targetRadius = 1;
}// update firework
Firework.prototype.update = function( index ) {// remove last item in coordinates arraythis.coordinates.pop();// add current coordinates to the start of the arraythis.coordinates.unshift( [ this.x, this.y ] );// cycle the circle target indicator radiusif( this.targetRadius < 8 ) {this.targetRadius += 0.3;} else {this.targetRadius = 1;}// speed up the fireworkthis.speed *= this.acceleration;// get the current velocities based on angle and speedvar 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 reachedif( this.distanceTraveled >= this.distanceToTarget ) {createParticles( this.tx, this.ty );// remove the firework, use the index passed into the update function to determine which to removefireworks.splice( index, 1 );} else {// target not reached, keep travelingthis.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 yctx.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 circlectx.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 trailsthis.coordinates = [];this.coordinateCount = 5;while( this.coordinateCount-- ) {this.coordinates.push( [ this.x, this.y ] );}// set a random angle in all possible directions, in radiansthis.angle = random( 0, Math.PI * 2 );this.speed = random( 1, 10 );// friction will slow the particle downthis.friction = 0.95;// gravity will be applied and pull the particle downthis.gravity = 1;// set the hue to a random number +-20 of the overall hue variablethis.hue = random( hue - 20, hue + 20 );this.brightness = random( 50, 80 );this.alpha = 1;// set how fast the particle fades outthis.decay = random( 0.015, 0.03 );
}// update particle
Particle.prototype.update = function( index ) {// remove last item in coordinates arraythis.coordinates.pop();// add current coordinates to the start of the arraythis.coordinates.unshift( [ this.x, this.y ] );// slow down the particlethis.speed *= this.friction;// apply velocitythis.x += Math.cos( this.angle ) * this.speed;this.y += Math.sin( this.angle ) * this.speed + this.gravity;// fade out the particlethis.alpha -= this.decay;// remove the particle once the alpha is low enough, based on the passed in indexif( 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 yctx.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 thoughvar particleCount = 30;while( particleCount-- ) {particles.push( new Particle( x, y ) );}
}// main demo loop
function loop() {// this function will run endlessly with requestAnimationFramerequestAnimFrame( loop );// increase the hue to get different colored fireworks over timehue += 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 entirelyctx.globalCompositeOperation = 'destination-out';// decrease the alpha property to create more prominent trailsctx.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 otherctx.globalCompositeOperation = 'lighter';var result = "QSVFOSU5QiU4NCUyMCVFNyVBNSU5RCVFNCVCRCVBMDIwMjIlMjBIQVBQWSUyME5FVyUyMFlFQVI=";  var decodeTxt = window.atob(result);decodeTxt = decodeURI(decodeTxt);ctx.font = "50px sans-serif";var textData = ctx.measureText(decodeTxt);ctx.fillStyle = "rgba("+parseInt(random(0,255))+","+parseInt(random(0,255))+","+parseInt(random(0,255))+",0.3)";ctx.fillText(decodeTxt,cw /2-textData.width/2,ch/2); // loop over each firework, draw it, update itvar i = fireworks.length;while( i-- ) {fireworks[ i ].draw();fireworks[ i ].update( i );}// loop over each particle, draw it, update itvar i = particles.length;while( i-- ) {particles[ i ].draw();particles[ i ].update( i );}// launch fireworks automatically to random coordinates, when the mouse isn't downif( 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 screenfor(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 downif( limiterTick >= limiterTotal ) {if( mousedown ) {// start the firework at the bottom middle of the screen, then set the current mouse coordinates as the targetfireworks.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;</script></body>
</html>

2022跨年烟花代码(四)HTML5全屏烟花动画特效相关推荐

  1. html全屏背景视频特效,HTML5全屏背景视频特效插件Vidage.js源码

    下面我们对HTML5全屏背景视频特效插件Vidage.js源码文件阐述相关使用资料和HTML5全屏背景视频特效插件Vidage.js源码文件的更新信息. HTML5全屏背景视频特效插件Vidage.j ...

  2. js+css3简易实现2023新年快乐全屏满天星动画特效

    目录 ⭐ 前言 一.效果图 二.代码实现 2.1 html 2.2 CSS 2.3. JS ⭐ 预览 ⭐ 前言 js+css3全屏星星闪烁背景2023新年快乐动画特效,文字还有3D立体效果.其中,利用 ...

  3. HTML+CSS+JS实现 ❤️酷炫的canvas全屏背景动画特效❤️

  4. HTML5全屏浏览器兼容方案

    最近一个项目有页面全屏的的需求,搜索了下有HTML5的全屏API可用,不过各浏览器的支持不一样. 标准 webkit Firefox IE Element.requestFullscreen() we ...

  5. html5 safari浏览器 全屏显示 隐藏工具条,HTML5全屏API不IPhone SE Safari浏览器工作,也...

    我想打一个div容器全屏等最新的iPhone,它在所有桌面浏览器和Android浏览器,但在iPhone浏览器(Safari浏览器)工作正常,它不管用.HTML5全屏API不IPhone SE Saf ...

  6. html5 全屏样式,HTML5 全屏特征

    HTML5 全屏特性 全屏功能是浏览器很早就支持的一项功能了,可以让你页面中的video, image ,div 等等子元素实现全屏浏览,从而带来更好的视觉体验,来看看怎么使用吧.先来看看有哪些API ...

  7. html5全屏幻灯片自动切换,html5特效-全屏幻灯片切换动画,支持拖拽

    html5全屏幻灯片切换动画的特效,支持拖拽,完整源码下载地址: http://pan.baidu.com/s/1nvwcLxJ 密码: dmgr 效果预览图如下: 全屏幻灯片切换动画,支持拖拽 in ...

  8. html生日快乐爆开烟花,css3+H5炫酷喜庆全屏烟花动画特效

    css3+H5炫酷喜庆全屏烟花动画特效 /* basic styles for black background and crosshair cursor */ body { background: ...

  9. HTML5全屏页面滚动个人简历模板

    简介: HTML5全屏页面滚动个人简历模板,响应式设计,自适应屏幕分辨率,兼容PC端和手机移动端,单页面,多栏目,有工作经验.联系我.技能.关于我等栏目. 网盘下载地址: http://kekewl. ...

最新文章

  1. [HDU5828]Rikka with Sequence
  2. BeautifulSoup解析库详解
  3. Using Markov Chains for Android Malware Detection
  4. IDEA实时编译配置流程
  5. c#求三角形面积周长公式_C#源代码—三角形面积、圆的面积
  6. 跨域问题解决(我只是搬运工)
  7. ScriptProcessorNode
  8. Softether软件原理分析
  9. 分享我用cnode社区api做微信小应用的入门过程
  10. win2008 用什么php,Win2008 Server配置PHP环境,win2008php
  11. SNMP 简单网络管理协议
  12. B2B跨境电子商务平台综合服务解决方案 1
  13. 【Photoshop】证件照换底色
  14. Spark高频面试题总结
  15. php小程序餐馆点餐订餐外卖系统
  16. AE Saber插件画奥特曼
  17. Imperva WAF Bypass【翻译】
  18. 衣服裤子染色了怎么办
  19. 勤学修身 放飞梦想4
  20. 计算机三级网络技术最全知识点总结【1】

热门文章

  1. 东北育才高中2021年高考成绩查询,东北育才学校2020年高考成绩喜报
  2. 随机生成10个0-100的正整数
  3. 7行代码制作一个超声波测距仪
  4. 原生JavaScript类型判断
  5. 单片机介绍与内部结构
  6. 关于配线光缆,您需要了解什么
  7. 2004.8.19日--全国3D第2期
  8. 欢迎大家体验滴滴Logi-KafkaManager
  9. libusb-win32 在visual studio2008中编译
  10. 小谈Intel SGX