cssbody { background: #00 " />

cssbody { background: #00"/>
 首页 > 作文

canvas烟花特效锦集

更新时间:2023-04-03 08:16:45 阅读: 评论:0

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 u requestanimationframe instead of ttimeout or tinterval// not supported in all browrs though and sometimes needs a prefix, so we need a shimwindow.requestanimframe = (function () {return window.requestanimationframe ||window.webkitrequestanimationframe ||window.mozrequestanimationframe ||function (callback) {window.ttimeout(callback, 1000 / 60);};})();// now we will tup our basic variables for the demovar 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,moudown = fal,// mou x coordinate,mx,// mou y coordinatemy;// t canvas dimensionscanvas.width = cw;canvas.height = ch;// now we are going to tup our function placeholders for the entire demo// get a random number within a rangefunction random(min, max) {return math.random() * (max - min) + min;}// calculate the distance between two pointsfunction calculatedistance(p1x, p1y, p2x, p2y) {var xdistance = p1x - p2x,ydistance = p1y - p2y;return math.sqrt(math.pow(xdistance, 2) + math.pow(ydistance, 2));}// create fireworkfunction 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, increa 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 fireworkfirework.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;} el {this.targetradius = 1;}// speed up the fireworkthis.speed *= this.acceleration;// get the current velocities bad 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, u the index pasd into the update function to determine which to removefireworks.splice(index, 1);} el {// target not reached, keep travelingthis.x += vx;this.y += vy;}}// draw fireworkfirework.prototype.draw = function () {ctx.beginpath();// move to the last tracked coordinate in the t, 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 particlefunction particle(x, y) {this.x = x;this.y = y;// track the past coordinates of each particle to create a trail effect, increa the coordinate count to create more prominent trailsthis.coordinates = [];this.coordinatecount = 5;while (this.coordinatecount--) {this.coordinates.push([this.x, this.y]);}// t 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;// t 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;// t how fast the particle fades outthis.decay = random(0.015, 0.03);}// update particleparticle.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, bad on the pasd in indexif (this.alpha <= this.decay) {particles.splice(index, 1);}}// draw particleparticle.prototype.draw = function () {ctx.beginpath();// move to the last tracked coordinates in the t, 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/explosionfunction createparticles(x, y) {// increa the particle count for a bigger explosion, beware of the canvas performance hit with the incread particles thoughvar par山西一本线2020ticlecount = 30;while (particlecount--) {particles.push(new particle(x, y));}}// main demo loopfunction loop() {// this function will run endlessly with requestanimationframerequestanimframe(loop);// increa the hue to get different colored fireworks over timehue += 0.5;// normally, clearrect() would be ud to clear the canvas// we want to create a trailing effect though// tting 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';// decrea 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 text = "happy new year !";ctx.font = "50px sans-rif";var textdata = ctx.measuretext(text);ctx.fillstyle = "rgba(" + parint(random(0, 255)) + "," + parint(random(0, 255)) + "," + parint(random(0,255)) + ",0.3)";ctx.filltext(text, 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 mou isn't downif (timertick >= timertotal) {if (!moudown) {// start the firework at the bottom middle of the screen, then t the random target coordinates, the random y coordinates will be t 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;}} el {timertick++;}// limit the rate at which fireworks get launched when mou is downif (limitertick >= limitertotal) {if (moudown) {// start the firework at the bottom middle of the screen, then t the current mou coordinates as the targetfireworks.push(new firework(cw / 2, ch / 2, mx, my));limitertick = 0;}} el {limitertick++;}}// mou event bindings// update the mou coordinates on moumovecanvas.addeventlistener('moumove', function (e) {mx = e.pagex - canvas.offtleft;my = e.pagey - canvas.offttop;});// toggle moudown state and prevent canvas from being lectedcanvas.addeventlistener('mou湿润反义词down', function (e) {e.preventdefault();moudown = true;});canvas.addeventlistener('mouup', function (e) {e.preventdefault();moudown = fal;});// 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-rif;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 ea 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.querylector('canvas').getcontext('2d')ctx.canvas.width = window.innerwidthctx.canvas.height = window.innerheightvar sparks = []var fireworks = []var i = 20;while (i--) {fireworks.push(new firework(math.random() * window.innerwidth, window.innerheight * math.random()))}render()function render() {ttimeout(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) continuefirework.move()firework.draw()}for (var spark of sparks) {if (spark.dead) continuespark.move()spark.draw()}if (math.random() < 0.05) {fireworks.push(new firework())}}function spark(x, y, color) {this.x = xthis.y = ythis.dir = math.random() * (math.pi * 2)this.dead = falthis.color = colorthis.speed = math.random() * 3 + 3;this.walker = new walker({radius: 20,speed: 0.25})this.gravity = 0.25this.dur = this.speed / 0.1this.move = function () {this.dur--if (this.dur < 0) this.dead = trueif (this.speed < 0) returnif (this.speed > 0) this.speed -= 0.1var walk = this.walker.step()this.x += math.cos(this.dir + walk) * this.speedthis.y += math.sin(this.dir + walk) * this.speedthis.y += this.gravitythis.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.widththis.y = y || ctx.canvas.heightthis.height = math.random() * ctx.canvas.height / 2this.dead = falthis.color = randomcolor()this.move = function () {this.x += this.xmove.step()if (this.y > this.height) this.y -= 1;el this.burst()}this.draw = function () {drawcircle(this.x, this.y, 1, this.color)}this.burst = function () {this.dead = truevar i = 100;while (i--) sparks.push(new spark(this.x, this.y, this.color))}}function drawcircle(x, y, radius, color) {color = color || '#fff'ctx.fill搞笑闪图style = colorctx.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.speedthis.value += this.directionthis.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 = 0this.value = 0this.radius = options.radiusthis.target = this.newtarget()this.direction = math.sign(this.target)this.wander = options.wanderthis.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 : fal;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)} el {var bigboom = new boom(getrandom(canvas.width / 3, canvas.width * 2 / 3), 2, "#fff", {x: canvas.width / 2,y: 200}, document.querylectorall(".shape")[parint(getrandom(0, document.querylectorall(".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();} el {this.booms.foreach(function (index) {if (!this.dead) {this.moveto(index);} el 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)} el {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.ttimeout(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 || fal;this.boomarea = boomarea;this.theta = 0;this.dead = fal;this.ba = parint(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();} el this._boom();this.dead = true;} el {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: parint(getrandom(128, 255)),b: parint(getrandom(128, 255)),c: parint(getrandom(128, 255))}}var fanwei = parint(getrandom(300, 400));for (var i = 0; i < fragnum; i++) {if (style === 2) {color = {a: parint(getrandom(128, 255)),b: parint(getrandom(128, 255)),c: parint(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);})} el {var text = ele.innerhtml;context.save();var fontsize = 200;context.font = fontsize + "px 宋体 bold";context.textalign = "center";context.textbaline = "middle";context.fillstyle = "rgba(" + parint(getrandom(128, 255)) + "," + parint(getrandom(128, 255)) + "," +parint(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);} el {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 = fal;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实现烟花动画,基本分为烟火类和碎屑类展现烟花的不同状态。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。

本文发布于:2023-04-03 08:16:43,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/8b641bdd898162e1f8d380898cd4d10f.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:canvas烟花特效锦集.doc

本文 PDF 下载地址:canvas烟花特效锦集.pdf

标签:烟花   几种   本文   效果
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图