您好,欢迎访问一九零五行业门户网

canvas怎样做出黑色背景的红色烟花

这次给大家带来canvas怎样做出黑色背景的红色烟花,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 shimwindow.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 demovar 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 dimensionscanvas.width = cw; canvas.height = ch;// now we are going to setup 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 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 fireworkfirework.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 fireworkfirework.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 particlefunction 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 particleparticle.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 particleparticle.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/explosionfunction 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 loopfunction 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 mousemovecanvas.addeventlistener('mousemove', function (e) { mx = e.pagex - canvas.offsetleft; my = e.pagey - canvas.offsettop; });// toggle mousedown state and prevent canvas from being selectedcanvas.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;
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
js中的async/await
react.js中的css使用
以上就是canvas怎样做出黑色背景的红色烟花的详细内容。
其它类似信息

推荐信息