PK creative Spring Festival, I am participating in the “Spring Festival creative submission contest”, please see: Spring Festival creative submission Contest

introduce

Canvas is a label in HTML. It is similar to the drawing tool of Window system in terms of its meaning and function. The only difference is that we need to use JS to render the desired effect

Entry three plate axe

  1. Define a Canvas tag on the DOM with length and width attributes
<canvas id="canvas" width="300px" height="300px" style="background:#000"></canvas>
Copy the code

To visualize the effect, give a background color

  1. Get the reference of “brush” on the corresponding canvas through JS. All subsequent drawing operations on canvas basically need to use this “brush”.
let cx = document.getElementById('canvas').getContext('2d')
Copy the code

Like the code, we got a 2D brush

  1. Use “brushes” to draw the shapes we need, such as basic lines, circles, matrices, etc
/ / draw circles
function drawArc(x, y, r) {
    cx.beginPath();
    cx.arc(x, y, r, 0.2 * Math.PI);
    cx.fill();
}
Draw a line / /
function drawLine(startX, startY, endX, endY) {
    cx.beginPath();
    cx.moveTo(startX, startY);
    cx.lineTo(endX, endY);
    cx.stroke();
    cx.closePath()
}
// cx.fillrect (x, y, width, height)
drawArc(50.50.10);
drawLine(50.70.50.200);
cx.fillRect(100.100.50.100)
Copy the code

Note: the coordinate system on the canvas has been marked in red in the figure above. The origin is the top left corner of the canvas, x to the right, y to the bottom

Because the canvas is a piece of paper, everything we draw on it will affect the result of the previous drawing, which is the overlay drawing. For example, in photoshop, every time we do it, we draw on top of the new layer; What’s worse than Photoshop is that you can’t change the previous layer.

Ok, now that we know a little bit about the canvas, let’s start doing some small things

Draw the fireworks

There are two stages to the familiar fireworks effect: (1) the firework rises rapidly, and (2) the firework rises to a certain point, explodes, and the resulting sparks scatter and disappear

One of the biggest effects of fireworks is tail flame drag. There are two ways to do this:

(1) For each trajectory drawing, solid line is used in the first half, and transparent line with gradual change is used in the second half;

② Take advantage of the overlay drawing feature of the canvas. Before each frame is drawn, the full layer is overlaid with a background color with transparency. After each overlay, the graphics on the canvas will be lightened.

In this example, plan 2 is adopted to periodically overlay transparent background color for the entire canvas, and the rest only needs to consider the position of the point to draw

Animate the ascent phase

Get the visible height of the page, set it to the starting point of the firework, get the random height of the ascent, and set a rate of ascent (i.e. a few pixels per frame).

let hz = 1000 / 75;
fireUp(200.2);
function fireUp(x, r) {
    let y = window.innerHeight;
    ramdomTop = parseInt(Math.random() * 500) + 100;
    let cleanT = setInterval(() = > clean(), hz*1.2);
    let time = setInterval(() = > {
        if (y < ramdomTop) {
            // clearInterval(time);
            y = window.innerHeight;
        }
        y -= 4;
        drawPoint(new Point(x, y, r))
    }, hz);
}
Copy the code

Draw the effect of fireworks scattering

The core is to use math.sin (), math.cos () to calculate the x and y coordinates of each Angle, and then modify the center point to obtain the coordinate relation of each Angle around the specified coordinate. Based on this relation, we can calculate the uniform motion trajectory of each Angle equally

// Calculate the data around the point
function caculatePoints(px, py, step, maxR) {
    /** * [p1-x] * [p2-x] */
    let arrs = [];
    for (let i = step; i <= 360; i += step) {
        arrs.push(new Point(Math.cos(Math.PI / 180 * i).toFixed(4),
            Math.sin(Math.PI / 180 * i).toFixed(4),
            2));
    }
    let arrs2 = [];
    for (let i = 1; i < maxR; i++) {
        arrs2.push(arrs.map(n= > new Point(n.x * i + px, n.y * i + py, n.r, n.color)));
    }
    return arrs2;
}
Copy the code

Insert the call to this function in the fireworks function

The effect is as shown in the picture:

Colorful bloom track

The effect is achieved, all white fireworks suddenly tired of watching, add a random color to the fireworks bloom effect

Because after blooming, the effect on each track is usually the same color or similar color, it is suitable to add this function to the function generated by the surrounding points

Modify using Point object, bind color. Define a function that generates random RGB

function Point(x, y, r = 2, color = '#fff') {
    return {
        x: x,
        y: y,
        r: r,
        color: color
    }
}
let rgb = function() {
    let str = ['1'.'2'.'3'.'4'.'5'.'6'.'7'.'8'.'9'.'a'.'b'.'c'.'d'.'e'.'f'];
    return {
        ramdon() {
            let color = The '#';
            for (let i = 0; i < 6; i++) {
                color += str[parseInt(Math.floor(Math.random() * 16))]}returncolor; }}} ();Copy the code

CaculatePoints () is passed random RGB when creating Point instances, with the following changes

The effect after modification is as follows:

highlight

How hard is it to go through all this trouble to make DOME, when it has to be on the nuggets?

Add random fireworks, and limit the maximum number of fireworks, the home page beautificated style:

Grease monkey link

New Year fireworks Background (gold-digging adaptation)

The script is simple and can be installed to achieve the same effect

To improve the

Add more random values to the effect of fireworks, such as the rate of rise, the radius of movement after the explosion

To improve

Bloom effect is still a little stiff, continue to study the acceleration of gravity, after the arrangement should be more beautiful


Original article, without permission, prohibit reprinting

-Leonard: Create by the comfort of salt fish