日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

html5烟花绽放效果

發(fā)布時(shí)間:2024/1/18 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 html5烟花绽放效果 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前端開發(fā)whqet,csdn,王海慶,whqet,前端開發(fā)專家

今天來(lái)看一個(gè)利用canvas+javascript實(shí)現(xiàn)的煙花綻放效果,大家可以到我的codepen看看DEMO,在線觀看或是下載研究,悉聽尊便。


首先來(lái)看看html,里面就放了一個(gè)canvas對(duì)象。

<!-- setup our canvas element --> <canvas id="canvas">Canvas is not supported in your browser.</canvas>css文件 body {background: #000;margin: 0; } canvas {cursor: crosshair;display: block; }

接著是JS,首先使用“RequestAnimationFrame”實(shí)現(xiàn)動(dòng)畫,可以有效解決setTimeout和setInterval的浪費(fèi)CPU問題。關(guān)于RequestAnimationFrame方法的特性和優(yōu)勢(shì),大家可以參考以下幾篇文章。

CSS-Tricks上的《Using requestAnimationFrame》

Treehouse Blog上的《Efficient Animations with requestAnimationFrame》

W3c的候選推薦標(biāo)準(zhǔn)《Timing control for script-based animations》

以及Erik M?ller提供的polyfill(在舊版瀏覽器上模擬標(biāo)準(zhǔn) API 的 JavaScript 補(bǔ)充)。

// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik M?ller. fixes from Paul Irish and Tino Zijdel // MIT license(function() {var lastTime = 0;var vendors = ['ms', 'moz', 'webkit', 'o'];for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];}if (!window.requestAnimationFrame)window.requestAnimationFrame = function(callback, element) {var currTime = new Date().getTime();var timeToCall = Math.max(0, 16 - (currTime - lastTime));var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);lastTime = currTime + timeToCall;return id;};if (!window.cancelAnimationFrame)window.cancelAnimationFrame = function(id) {clearTimeout(id);}; }());本案例需要兩個(gè)類煙花沫粒子和煙花。首先來(lái)看煙花沫類 // 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(); }

生成粒子的函數(shù)

// 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 ) );} }煙花類 // 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(); }定義好了主要的類,我們來(lái)設(shè)置一些常見的變量和函數(shù)。 // 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 ) ); }不斷釋放煙花的函數(shù),需要利用RequestAnimationFrame不斷地執(zhí)行函數(shù)。 // 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';// 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 screenfireworks.push( new Firework( 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 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, mx, my ) );limiterTick = 0;}} else {limiterTick++;} }綁定鼠標(biāo)事件 // 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; });在窗口加載完畢,單擊鼠標(biāo)前,我們也需要一些煙花 // once the window loads, we are ready for some fireworks! window.onload = loop;

完畢。

---------------------------------------------------------------

前端開發(fā)whqet,關(guān)注web前端開發(fā)技術(shù),分享網(wǎng)頁(yè)相關(guān)資源。
---------------------------------------------------------------

總結(jié)

以上是生活随笔為你收集整理的html5烟花绽放效果的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 亚洲成a人片77777精品 | 成人黄色在线观看 | 国产一卡二卡在线播放 | 里番精品3d一二三区 | 超碰超在线 | 国产精品福利影院 | 成年人在线观看视频 | 岛国av电影在线观看 | 精品国产中文字幕 | 亚洲精品热 | 亚洲精品色图 | 国产又粗又长又黄视频 | 国产精品国产三级国产a | 日韩孕交| 丰满少妇被猛烈进入无码 | 亚洲 欧美 日韩 在线 | 欧美一区二区三区国产 | 婷婷第四色 | 激情久久久 | 日韩网站在线播放 | 日韩天堂av | 麻豆一区二区99久久久久 | 成人黄色免费网址 | 国产日韩av在线播放 | 免费网站在线观看黄色 | 成人国产精品 | 久久综合五月婷婷 | 黄色精品 | 嫩草一区 | 国产精品乱码一区二区视频 | 99久久久无码国产精品性黑人 | 用我的手指扰乱你 | 亚洲精品久久久久久动漫器材一区 | 麻豆一区二区三区四区 | 日本视频在线免费 | 久草这里只有精品 | 少妇丰满尤物大尺度写真 | 欧美视频一区二区在线观看 | 久久精品无码一区二区三区毛片 | 97国产精东麻豆人妻电影 | yes4444视频在线观看 | 国产亚洲精品久久久久四川人 | 尤物视频在线 | 黄色.com| 青青草免费在线观看视频 | 男女爱爱动态图 | 久久福利影院 | 嫩草影院在线观看视频 | 肥臀浪妇太爽了快点再快点 | 国产又大又黄又粗 | 国产一区二区免费电影 | 大陆极品少妇内射aaaaaa | 亚洲h视频在线观看 | 亚洲女优视频 | 精品国产一二三区 | 制服丝袜一区 | 天堂在线免费视频 | 国产人妻精品久久久久野外 | 色 综合 欧美 亚洲 国产 | 97人妻人人澡人人爽人人精品 | 欧美性极品少妇xxxx | 亚洲二级片| 精品久久久久成人码免费动漫 | 亚洲a网站 | 国产精彩视频一区二区 | 免费a级大片 | 久久丫精品忘忧草西安产品 | 久久av红桃一区二区小说 | 亚洲午夜网 | 天堂在线播放 | 日韩精品视频免费在线观看 | 天天狠天天插天天透 | av老司机在线观看 | 国产精品九九九九九 | 特大黑人巨交吊性xx | 四虎永久免费在线观看 | 一区二区的视频 | 成人高清 | 香蕉视频在线观看免费 | 人人澡澡人人 | 色诱视频在线观看 | 亚洲综合影院 | 另类天堂网 | 在线视频国产一区 | 免费av地址 | 亚洲视频图片小说 | 亚洲黄片一区二区三区 | 国产wwww | 成人黄色一区二区三区 | 依依成人综合网 | 韩日一级片 | 花房姑娘免费全集 | 亚洲精品无码一区二区 | 欧美日本二区 | 天堂网在线最新版www中文网 | 耳光调教vk | 国产男男gay网站 | 91久久精品夜夜躁日日躁欧美 | 污视频网址 |