canvas烟花特效锦集
程序员文章站
2023-11-29 15:28:22
这篇文章主要介绍了canvas烟花特效锦集,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧... 18-01-17...
canvas可以实现不同动画效果,本文主要记录几种不同节日烟花效果实现。
实现一
html
<canvas id="canvas"></canvas>
css
body { background: #000; margin: 0; } canvas { cursor: crosshair; display: block; }
js
// 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 dimensions cw = window.innerwidth, ch = window.innerheight, // firework collection fireworks = [], // particle collection particles = [], // starting hue hue = 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 x coordinate, mx, // mouse y coordinate my; // 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 coordinates this.x = sx; this.y = sy; // starting coordinates this.sx = sx; this.sy = sy; // target coordinates this.tx = tx; this.ty = ty; // distance from starting point to target this.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 trails this.coordinates = []; this.coordinatecount = 3; // populate initial coordinate collection with the current coordinates while (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 radius this.targetradius = 1; } // update firework firework.prototype.update = function (index) { // remove last item in coordinates array this.coordinates.pop(); // add current coordinates to the start of the array this.coordinates.unshift([this.x, this.y]); // cycle the circle target indicator radius if (this.targetradius < 8) { this.targetradius += 0.3; } else { this.targetradius = 1; } // speed up the firework this.speed *= this.acceleration; // get the current velocities based on angle and speed var 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 reached if (this.distancetraveled >= this.distancetotarget) { createparticles(this.tx, this.ty); // remove the firework, use the index passed into the update function to determine which to remove fireworks.splice(index, 1); } else { // target not reached, keep traveling this.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 y ctx.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 circle ctx.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 trails this.coordinates = []; this.coordinatecount = 5; while (this.coordinatecount--) { this.coordinates.push([this.x, this.y]); } // set a random angle in all possible directions, in radians this.angle = random(0, math.pi * 2); this.speed = random(1, 10); // friction will slow the particle down this.friction = 0.95; // gravity will be applied and pull the particle down this.gravity = 1; // set the hue to a random number +-20 of the overall hue variable this.hue = random(hue - 20, hue + 20); this.brightness = 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 coordinates array this.coordinates.pop(); // add current coordinates to the start of the array this.coordinates.unshift([this.x, this.y]); // slow down the particle this.speed *= this.friction; // apply velocity this.x += math.cos(this.angle) * this.speed; this.y += math.sin(this.angle) * this.speed + this.gravity; // 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); } } // 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 y ctx.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 though var particlecount = 30; while (particlecount--) { particles.push(new particle(x, y)); } } // main demo loop function loop() { // this function will run endlessly with requestanimationframe requestanimframe(loop); // increase the hue to get different colored fireworks over time hue += 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'; var text = "happy new year !"; ctx.font = "50px sans-serif"; var textdata = ctx.measuretext(text); ctx.fillstyle = "rgba(" + parseint(random(0, 255)) + "," + parseint(random(0, 255)) + "," + parseint(random(0, 255)) + ",0.3)"; ctx.filltext(text, cw / 2 - textdata.width / 2, ch / 2); // loop over each firework, draw it, update it var i = fireworks.length; while (i--) { fireworks[i].draw(); fireworks[i].update(i); } // loop over each particle, draw it, update it var i = particles.length; while (i--) { particles[i].draw(); particles[i].update(i); } // launch fireworks automatically to random coordinates, when the mouse isn't down if (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 screen for (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 down if (limitertick >= limitertotal) { if (mousedown) { // start the firework at the bottom middle of the screen, then set the current mouse coordinates as the target fireworks.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;
实现二
html
<canvas></canvas> <h1>201<span>8</span></h1>
css
html, body { padding: 0px; margin: 0px; background: #222; font-family: 'karla', sans-serif; color: #fff; height: 100%; overflow: hidden; } h1 { z-index: 1000; position: fixed; top: 50%; left: 50%; transform: translatex(-50%) translatey(-100%); font-size: 58px; overflow: hidden; } span { position: relative; display: inline-block; animation: drop 0.75s ease 0s; } canvas { width: 100%; height: 100%; } @keyframes drop { 0% { transform: translatey(-100px); opacity: 0; } 90% { opacity: 1; transform: translatey(10px); } 100% { transform: translatey(0px); } }
js
var ctx = document.queryselector('canvas').getcontext('2d') ctx.canvas.width = window.innerwidth ctx.canvas.height = window.innerheight var sparks = [] var fireworks = [] var i = 20; while (i--) { fireworks.push( new firework(math.random() * window.innerwidth, window.innerheight * math.random()) ) } render() function render() { settimeout(render, 1000 / 60) ctx.fillstyle = 'rgba(0, 0, 0, 0.1)'; ctx.fillrect(0, 0, ctx.canvas.width, ctx.canvas.height) for (var firework of fireworks) { if (firework.dead) continue firework.move() firework.draw() } for (var spark of sparks) { if (spark.dead) continue spark.move() spark.draw() } if (math.random() < 0.05) { fireworks.push(new firework()) } } function spark(x, y, color) { this.x = x this.y = y this.dir = math.random() * (math.pi * 2) this.dead = false this.color = color this.speed = math.random() * 3 + 3; this.walker = new walker({ radius: 20, speed: 0.25 }) this.gravity = 0.25 this.dur = this.speed / 0.1 this.move = function () { this.dur-- if (this.dur < 0) this.dead = true if (this.speed < 0) return if (this.speed > 0) this.speed -= 0.1 var walk = this.walker.step() this.x += math.cos(this.dir + walk) * this.speed this.y += math.sin(this.dir + walk) * this.speed this.y += this.gravity this.gravity += 0.05 } this.draw = function () { drawcircle(this.x, this.y, 3, this.color) } } function firework(x, y) { this.xmove = new walker({ radius: 10, speed: 0.5 }) this.x = x || math.random() * ctx.canvas.width this.y = y || ctx.canvas.height this.height = math.random() * ctx.canvas.height / 2 this.dead = false this.color = randomcolor() this.move = function () { this.x += this.xmove.step() if (this.y > this.height) this.y -= 1; else this.burst() } this.draw = function () { drawcircle(this.x, this.y, 1, this.color) } this.burst = function () { this.dead = true var i = 100; while (i--) sparks.push(new spark(this.x, this.y, this.color)) } } function drawcircle(x, y, radius, color) { color = color || '#fff' ctx.fillstyle = color ctx.fillrect(x - radius / 2, y - radius / 2, radius, radius) } function randomcolor() { return ['#6ae5ab', '#88e3b2', '#36b89b', '#7bd7ec', '#66cbe1'][math.floor(math.random() * 5)]; } function walker(options) { this.step = function () { this.direction = math.sign(this.target) * this.speed this.value += this.direction this.target ? this.target -= this.direction : (this.value) ? (this.wander) ? this.target = this.newtarget() : this.target = -this.value : this.target = this.newtarget() return this.direction } this.newtarget = function () { return math.round(math.random() * (this.radius * 2) - this.radius) } this.start = 0 this.value = 0 this.radius = options.radius this.target = this.newtarget() this.direction = math.sign(this.target) this.wander = options.wander this.speed = options.speed || 1 }
实现三
html
<canvas id="cas" style="background-color:rgba(0,5,24,1)" width="1235" height="680">浏览器不支持canvas</canvas> <div class="city"> <img src="city.png" alt=""> </div> <img src="moon.png" alt="" id="moon" style="visibility: hidden;"> <div style="display:none"> <div class="shape">新年快乐</div> <div class="shape">阖家欢乐</div> <div class="shape">万事如意</div> <div class="shape">心想事成</div> </div>
css
body { margin: 0; padding: 0; overflow: hidden; } .city { width: 100%; position: fixed; bottom: 0px; z-index: 100; } .city img { width: 100%; }
js
var canvas = document.getelementbyid("cas"); var ocas = document.createelement("canvas"); var octx = ocas.getcontext("2d"); var ctx = canvas.getcontext("2d"); ocas.width = canvas.width = window.innerwidth; ocas.height = canvas.height = window.innerheight; var bigbooms = []; window.onload = function () { initanimate() } function initanimate() { drawbg(); lasttime = new date(); animate(); } var lasttime; function animate() { ctx.save(); ctx.fillstyle = "rgba(0,5,24,0.1)"; ctx.fillrect(0, 0, canvas.width, canvas.height); ctx.restore(); var newtime = new date(); if (newtime - lasttime > 500 + (window.innerheight - 767) / 2) { var random = math.random() * 100 > 2 ? true : false; var x = getrandom(canvas.width / 5, canvas.width * 4 / 5); var y = getrandom(50, 200); if (random) { var bigboom = new boom(getrandom(canvas.width / 3, canvas.width * 2 / 3), 2, "#fff", { x: x, y: y }); bigbooms.push(bigboom) } else { var bigboom = new boom(getrandom(canvas.width / 3, canvas.width * 2 / 3), 2, "#fff", { x: canvas.width / 2, y: 200 }, document.queryselectorall(".shape")[parseint(getrandom(0, document.queryselectorall( ".shape").length))]); bigbooms.push(bigboom) } lasttime = newtime; } stars.foreach(function () { this.paint(); }) drawmoon(); bigbooms.foreach(function (index) { var that = this; if (!this.dead) { this._move(); this._drawlight(); } else { this.booms.foreach(function (index) { if (!this.dead) { this.moveto(index); } else if (index === that.booms.length - 1) { bigbooms[bigbooms.indexof(that)] = null; } }) } }); raf(animate); } function drawmoon() { var moon = document.getelementbyid("moon"); var centerx = canvas.width - 200, centery = 100, width = 80; if (moon.complete) { ctx.drawimage(moon, centerx, centery, width, width) } else { moon.onload = function () { ctx.drawimage(moon, centerx, centery, width, width) } } var index = 0; for (var i = 0; i < 10; i++) { ctx.save(); ctx.beginpath(); ctx.arc(centerx + width / 2, centery + width / 2, width / 2 + index, 0, 2 * math.pi); ctx.fillstyle = "rgba(240,219,120,0.005)"; index += 2; ctx.fill(); ctx.restore(); } } array.prototype.foreach = function (callback) { for (var i = 0; i < this.length; i++) { if (this[i] !== null) callback.apply(this[i], [i]) } } var raf = window.requestanimationframe || window.webkitrequestanimationframe || window.mozrequestanimationframe || window.orequestanimationframe || window.msrequestanimationframe || function (callback) { window.settimeout(callback, 1000 / 60); }; canvas.onclick = function () { var x = event.clientx; var y = event.clienty; var bigboom = new boom(getrandom(canvas.width / 3, canvas.width * 2 / 3), 2, "#fff", { x: x, y: y }); bigbooms.push(bigboom) } var boom = function (x, r, c, boomarea, shape) { this.booms = []; this.x = x; this.y = (canvas.height + r); this.r = r; this.c = c; this.shape = shape || false; this.boomarea = boomarea; this.theta = 0; this.dead = false; this.ba = parseint(getrandom(80, 200)); } boom.prototype = { _paint: function () { ctx.save(); ctx.beginpath(); ctx.arc(this.x, this.y, this.r, 0, 2 * math.pi); ctx.fillstyle = this.c; ctx.fill(); ctx.restore(); }, _move: function () { var dx = this.boomarea.x - this.x, dy = this.boomarea.y - this.y; this.x = this.x + dx * 0.01; this.y = this.y + dy * 0.01; if (math.abs(dx) <= this.ba && math.abs(dy) <= this.ba) { if (this.shape) { this._shapboom(); } else this._boom(); this.dead = true; } else { this._paint(); } }, _drawlight: function () { ctx.save(); ctx.fillstyle = "rgba(255,228,150,0.3)"; ctx.beginpath(); ctx.arc(this.x, this.y, this.r + 3 * math.random() + 1, 0, 2 * math.pi); ctx.fill(); ctx.restore(); }, _boom: function () { var fragnum = getrandom(30, 200); var style = getrandom(0, 10) >= 5 ? 1 : 2; var color; if (style === 1) { color = { a: parseint(getrandom(128, 255)), b: parseint(getrandom(128, 255)), c: parseint(getrandom(128, 255)) } } var fanwei = parseint(getrandom(300, 400)); for (var i = 0; i < fragnum; i++) { if (style === 2) { color = { a: parseint(getrandom(128, 255)), b: parseint(getrandom(128, 255)), c: parseint(getrandom(128, 255)) } } var a = getrandom(-math.pi, math.pi); var x = getrandom(0, fanwei) * math.cos(a) + this.x; var y = getrandom(0, fanwei) * math.sin(a) + this.y; var radius = getrandom(0, 2) var frag = new frag(this.x, this.y, radius, color, x, y); this.booms.push(frag); } }, _shapboom: function () { var that = this; putvalue(ocas, octx, this.shape, 5, function (dots) { var dx = canvas.width / 2 - that.x; var dy = canvas.height / 2 - that.y; for (var i = 0; i < dots.length; i++) { color = { a: dots[i].a, b: dots[i].b, c: dots[i].c } var x = dots[i].x; var y = dots[i].y; var radius = 1; var frag = new frag(that.x, that.y, radius, color, x - dx, y - dy); that.booms.push(frag); } }) } } function putvalue(canvas, context, ele, dr, callback) { context.clearrect(0, 0, canvas.width, canvas.height); var img = new image(); if (ele.innerhtml.indexof("img") >= 0) { img.src = ele.getelementsbytagname("img")[0].src; imgload(img, function () { context.drawimage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.width / 2); dots = getimgdata(canvas, context, dr); callback(dots); }) } else { var text = ele.innerhtml; context.save(); var fontsize = 200; context.font = fontsize + "px 宋体 bold"; context.textalign = "center"; context.textbaseline = "middle"; context.fillstyle = "rgba(" + parseint(getrandom(128, 255)) + "," + parseint(getrandom(128, 255)) + "," + parseint(getrandom(128, 255)) + " , 1)"; context.filltext(text, canvas.width / 2, canvas.height / 2); context.restore(); dots = getimgdata(canvas, context, dr); callback(dots); } } function imgload(img, callback) { if (img.complete) { callback.call(img); } else { img.onload = function () { callback.call(this); } } } function getimgdata(canvas, context, dr) { var imgdata = context.getimagedata(0, 0, canvas.width, canvas.height); context.clearrect(0, 0, canvas.width, canvas.height); var dots = []; for (var x = 0; x < imgdata.width; x += dr) { for (var y = 0; y < imgdata.height; y += dr) { var i = (y * imgdata.width + x) * 4; if (imgdata.data[i + 3] > 128) { var dot = { x: x, y: y, a: imgdata.data[i], b: imgdata.data[i + 1], c: imgdata.data[i + 2] }; dots.push(dot); } } } return dots; } function getrandom(a, b) { return math.random() * (b - a) + a; } var maxradius = 1, stars = []; function drawbg() { for (var i = 0; i < 100; i++) { var r = math.random() * maxradius; var x = math.random() * canvas.width; var y = math.random() * 2 * canvas.height - canvas.height; var star = new star(x, y, r); stars.push(star); star.paint() } } var star = function (x, y, r) { this.x = x; this.y = y; this.r = r; } star.prototype = { paint: function () { ctx.save(); ctx.beginpath(); ctx.arc(this.x, this.y, this.r, 0, 2 * math.pi); ctx.fillstyle = "rgba(255,255,255," + this.r + ")"; ctx.fill(); ctx.restore(); } } var focallength = 250; var frag = function (centerx, centery, radius, color, tx, ty) { this.tx = tx; this.ty = ty; this.x = centerx; this.y = centery; this.dead = false; this.centerx = centerx; this.centery = centery; this.radius = radius; this.color = color; } frag.prototype = { paint: function () { ctx.save(); ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, 2 * math.pi); ctx.fillstyle = "rgba(" + this.color.a + "," + this.color.b + "," + this.color.c + ",1)"; ctx.fill() ctx.restore(); }, moveto: function (index) { this.ty = this.ty + 0.3; var dx = this.tx - this.x, dy = this.ty - this.y; this.x = math.abs(dx) < 0.1 ? this.tx : (this.x + dx * 0.1); this.y = math.abs(dy) < 0.1 ? this.ty : (this.y + dy * 0.1); if (dx === 0 && math.abs(dy) <= 80) { this.dead = true; } this.paint(); } }
总结
几种不同canvas实现烟花动画,基本分为烟火类和碎屑类展现烟花的不同状态。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 详解Html5原生拖拽操作