Canvas series three fireworks effect implementation

Write first:

Alas, time is really fast ah, the distance from the last demo is already half a month ago, the original thought is to write a weekly, but the previous period of time work slightly busy, so there is no demo output (hey hey, secretly to find an excuse for their own, also do not know later can insist on output……) . This time, I wrote a demo of setting off fireworks on canvas. I feel like I’m going to write one or two more demos and make a final summary of this thing. After all, it’s not a thing to write demos all the time. I have to summarize the canvas. All right, without further ado, let’s cut to the chase

By the way, please give my blog a thumbs up and ask for a star

Results show

Git address:

Github.com/ry928330/fi…

Implementation idea:

As usual, we will present the implementation process of this fireworks demo in the form of a question. You can also use these questions to imagine how it can be implemented as you read.

  • The generation of fireworks and disappear, basically is how to achieve the kind of meteor across the trailing effect?
  • After the fireworks disappear, how to produce the effect of scattering after the explosion?
  • How do scattered sparks produce the effect of falling and disappearing under the influence of gravity?

Basically, you’ve done the above three steps, and your fireworks effect is done. Haha, it’s very simple. So let’s do it one by one.

Details:

The birth and disappearance of fireworks:

Those of you who have seen one of my previous Canvas series, or who know about Canvas animation, must know how an element drawn inside a canvas moves. Are we constantly using the clearReact function to help us clear the previous frame of the animation? In fact, what if instead of completely removing the previous frame, we “covered” it with a more transparent color? Ha ha ha, is not very simple, in fact, a code:

ctx.fillStyle = 'rgba (0,0,0,0.05)';Copy the code

If you want the tail to be long, you make the transparency smaller, if you want the tail to be short, you make the transparency bigger. Next, the disappearance of fireworks. For each firework, we declare it as an object that contains the size of the firework, the position of the firework, and the firework’s drawing to the movement function. The initial value of disappear is false, indicating that a firework is still “alive”. We can set some boundary conditions. In this demo, the distance boundary is used, that is, when the fireworks move beyond the range I set, the variable Disappear is set to true, indicating that the fireworks have knelt. Because I want to keep generating fireworks, I use an array to store the number of fireworks I already have. New fireworks are constantly pushed into the array, and missing fireworks are constantly removed from the array. Post my code:

if (fireArr.length) {
    fireArr.forEach(function(item, index) {
        var marginWidthLeft =  parseInt(getRandom(0, canvas.width/5), 10);
        var marginWidthRight = parseInt(getRandom(1500, canvas.width), 10);
        var marginHeight = parseInt(getRandom(0, 300), 10);
        if (item.x >= marginWidthRight || item.x <=  marginWidthLeft || item.y <= marginHeight) {
            item.disappear = true;
        }
        if(! item.disappear) { item.draw(); item.move(); }else {
            var removeFire = fireArr.splice(index, 1);
            fragments.push(removeFire);
            if (fragments.length) {
                fragments.forEach(function(item, index) {
                    if (item[0].boomJudge) {
                        item[0].boom();
                        item[0].boomJudge = false; } }) } fireArr.push(createRandomFire(CreateFireObj)); }})}Copy the code

So here I set the left and right and the top bounds, and both get random values within a certain range. When disappear becomes true, the element is removed from the array, and new elements are added later to ensure that there isa fixed number of fireworks on the page.

The disappearance of fireworks and the creation of an explosive effect:

This is the difficulty of this demo, but also the focus. How do you create lots and lots of little fireworks just as the fireworks disappear? How do small fireworks explode? At the beginning I was also confused, and then thinking about thinking about slowly some ideas.

For each firework, I added an explosion function boom. The function of this boom function is to generate a random number of small fires instantly when the firework disappears, that is, when it explodes (in fact, we can control the number randomly within a range). For each small fire, the color is random, and I generated a target position for it to reach when it was born. This target location is centered on the location of the fireworks explosion, and the radius is random. Using the equation of the circle, a random Angle is given, so that small sparks can be generated at the random location of the arc line with the location of the fireworks explosion as the center and random radius. For ease of management, each firework has an array variable called fragArr, which stores these newly generated fires. Each spark is also an object, and like a firework, it contains information about the size, position, movement function, draw function, and end of movement. The relevant codes are as follows:

// Fireworks explode, creating debris this.boom =function() {
    var scope = Math.round(getRandom(10, 40));
    for (var i=0; i<scope; i++) {
        var angel = getRandom(0, 2*Math.PI);
        var range = Math.round(getRandom(50, 300));
        var targetX = this.x + range*Math.cos(angel);
        var targetY = this.y + range*Math.sin(angel);
        var r = Math.round(getRandom(120, 255));
        var g = Math.round(getRandom(120, 255));
        var b = Math.round(getRandom(120, 255));
        var color = 'rgb(' + r + ', ' + g + ', ' + b + ') '; var frag = new CreateFrag(this.x, this.y, color, targetX, targetY); this.fragArr.push(frag); }}Copy the code

The falling and disappearance of scattered fireworks:

Then above, at the moment of the explosion we use the boom function to generate a random number of small fires, each of which is generated using the CreateFrag function. Let’s focus on the movement function of small sparks in this function, because it produces the effect of small sparks falling like “gravity”. The code is as follows:

function CreateFrag(x, y, color, tx, ty) {
    var that = this
    that.x = x;
    that.y = y;
    that.ty = ty;
    that.tx = tx;
    that.color = color;
    that.disappear = false;
    that.draw = function() {
        ctx.save();
        ctx.beginPath();
        ctx.fillStyle = that.color;
        ctx.fillRect(that.x, that.y, 2, 2);
        ctx.restore();
    }
    that.move = function() {that.ty = that.ty + 0.5; var dx = that.tx - that.x, dy = that.ty - that.y; That. X = math.abs (dx) < 0.1? Tx: (that. X + dx*0.01); That. Y = math.abs (dy) < 0.1? Ty: (that. Y + dy*0.01);if (dx == 0 || dy == 0 || that.y >= 700 || that.x <= 300 || that.x >= 1700) {
            that.fragDisappear = true; }}}Copy the code

Function takes five parameters, two behind the tx and ty, represents the goal point x, y coordinates, we gave a his current position and target position difference, dx and dy, in the scope of this difference not more than a given threshold (0.1) we have here is, small spark of horizontal ordinate are increased 0.01 times that of dx and dy The smaller the multiple, the more detail the firework “explodes.” So we’re going to give it a good value. Ty = that.ty + 0.5. Without this code, the fire moves in a straight line, which means that its vertical velocity increases, giving it a vertical acceleration that makes it look like it’s being pulled down by gravity. For the disappearance of the petard, and actually disappear principle is the same as the fireworks, is petard reaches a certain boundary let it disappear, but the difference is one of a group of petard when fireworks to boundary conditions, I will kill the petard flowers in the array, not a a petard removal alone, put down the code:

var removeFire = fireArr.splice(index, 1);
fragments.push(removeFire);
if (fragments.length) {
    fragments.forEach(function(item, index) {
        if (item[0].boomJudge) {
            item[0].boom();
            item[0].boomJudge = false; }})}if (fragments.length) {
    fragments.forEach(function(item1, index1) {
        item1[0].fragArr.forEach(function(item2, index2) {
            if(item2.fragDisappear) { fragments.splice(index1, 1); } item2.draw(); item2.move(); })})}Copy the code

The fragments array stores the fireworks that have been removed. It is important to note that we use item1[0] instead of Item1 in fragments.forEach because when we store discarded fireworks, Var removeFire = firearr.splice (index, 1); fragments.push(removeFire); Fragments push the return value of fireArr Splice, which is an array with a single element.

After such a simple trilogy, our fireworks can be gorgeous in the air explosion, how, now look back to see if it is very simple.

Write at the end:

The above is only a simple fireworks to achieve the effect of the explosion, in fact, there are many areas can be improved. For example, when a firework goes up, instead of limiting its movement to a certain range, it can explode when its vertical velocity is reduced to zero by the influence of gravity. And we can add an audio clip that simulates the sound of fireworks exploding, and so on. These are all areas worth improving. Finally, thank you guys for taking time out of your busy schedule to read this piece of my share. Please be sure to give my blog a thumbs up. Your thumbs up will be an inexhaustible driving force for me to move forward