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

Life is not only the casual, there are poems and distant

Dig friends, everyone good I am front-end milk dad, into the line of 5 years of front-end primary school ๐Ÿฅœ~ work eight hours touch fish four hours, like running but not to make yourself thinner, but to make yourself live longer ~ live to ninety-nine, roll to ninety-nine ~

preface

The old saying is good, after the laba is ๐Ÿฅข

About to celebrate the New Year, small partners are restless ๐Ÿ”ฅ

In order to enhance the flavor of the New Year, the platform released a New Year activity, I also participate in a wave ~๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰

On the most interesting thing about Chinese New Year, I think the first thought is to set off firecrackers, when the family was poor, firecrackers can only buy a few whips, but also to different times for the normal ceremony set off, leaving the children to play will be very few.

So after the home to buy firecrackers, will be removed from the big hang one by one, and then take a thick incense. New Year’s Eve early in the morning to change new clothes, and a few small friends out to play, the left pocket full of candy (PS: We would go to dry Wells, ponds, and various places in the village to do some interesting explosion tests, and we would take firecrackers to scare little girls (PS: try not to do so).

Now the sound of firecrackers is less and less Chinese New Year, a few years ago outside Beijing’s fifth ring Road can also be set off, but from the beginning of this year is also a comprehensive ban, now some places in the village do not burn coal, the government provides unified heating. Most of the village is also weather pipes, so it is not allowed to set off fireworks, the feeling of missing a lot of Chinese New Year.

I still remember how excited duoduo was when she saw the fireworks for the first time last year, staring out of the window. This year, the government does not allow fireworks, so let’s make a simple fireworks with canvas. I hope she will like it ~๐Ÿ’—

The specific implementation

The canvas to create

Start with creating a Canvas element in HTML

<body>
  <canvas id="canvas"></canvas>
  <script src="https://s1.pstatp.com/cdn/expire-1-M/jquery/1.10.2/jquery.min.js"></script>
  <script src="./index.js"></script>
</body>
Copy the code
  • To save time, I just introduced itjqueryOpen accessdomAnd event binding operations.

Initialize the canvas

  • To obtaincanvasObject and assign width and height to full screen mode.
  • By listeningwindows ็š„ resizeThe dynamic changecanvasWidth and height, as well as the specific coordinates of key locations.
  • Initializes the canvas, sets the canvas initial properties.
const canvas = $("#canvas") [0];
canvas.width = $(window).width();
canvas.height = $(window).height();
const ctx = canvas.getContext("2d");

// Listen for window changes
$(window).on("resize".function () {
canvas.width = $(window).width();
canvas.height = $(window).height();
ctx.fillStyle = "# 000";
ctx.fillRect(0.0, canvas.width, canvas.height);
center = { x: canvas.width / 2.y: canvas.height / 2 };
});

// Initialize the canvas
ctx.fillStyle = "# 000";
ctx.fillRect(0.0, canvas.width, canvas.height);
Copy the code

Defining the draw material

  • Defines the content string for drawing text.
  • Initialize the position array to arrange the text on the canvas.
  • Create a matrix position array to draw letters.
// Initialize the underlying object
const listText = []; // The canvas fills the particle array
const fireNumber = 10; // Initializes the particle cardinality
const center = { x: canvas.width / 2.y: canvas.height / 2 }; // The current center of the canvas
const range = 100; // Particle animation range
let textIndex = 0; // Particle animation index

// Define to draw text content
const textString = "happynewyear2022";

// Array of initial positions
const textMatrix = [
    4.5.0.5.5.0.6.5.0.7.5.0.8.5.0.3.1.4.1.5.1.7.1.8.1.9.1.10.1.5.2.6.2.7.2.8.2,];// letter matrix position
const chars = {
    h: [
      0.0.0.1.0.2.0.3.0.4.0.5.0.6.0.7.1.3.2.3.3.3.4.3.5.0.5.1.5.2.5.3.5.4.5.5.5.6.5.7,].a: [
      2.0.2.1.2.2.1.2.1.3.1.4.1.5.0.5.0.6.0.7.2.5.3.0.3.1.3.2.4.2.4.3.4.4.4.1.5.5.5.6.5.7.3.5,].p: [
      0.0.0.1.0.2.0.3.0.4.0.5.0.6.0.7.1.0.2.0.3.0.4.1.5.2.4.3.3.4.2.4.1.4,].y: [
      0.0.0.1.1.1.1.2.2.2.2.3.3.3.3.4.3.5.3.6.3.7.4.3.4.2.5.2.5.1.6.1.6.0,].n: [
      0.0.0.1.0.2.0.3.0.4.0.5.0.6.0.7.1.1.1.2.2.2.2.3.2.4.3.4.3.5.4.5.4.6.5.0.5.1.5.2.5.3.5.4.5.5.5.6.5.7,].e: [
      0.0.0.1.0.2.0.3.0.4.0.5.0.6.0.7.1.0.2.0.3.0.4.0.5.0.1.3.2.3.3.3.4.3.1.7.2.7.3.7.4.7.5.7,].w: [
      0.0.0.1.0.2.0.3.0.4.0.5.0.6.1.6.1.7.2.7.3.7.3.5.6.3.5.5.3.5.4.3.5.3.3.5.2.3.5.1.4.7.5.7.6.7.6.6.7.6.7.5.7.4.7.3.7.2.7.1.7.0,].r: [
      0.0.0.1.0.2.0.3.0.4.0.5.0.6.0.7.1.0.2.0.3.0.4.1.5.2.4.3.3.4.2.4.1.4.1.5.2.5.3.6.4.6.5.7,].0: [
      0.1.0.2.0.3.0.4.0.5.0.6.1.0.2.0.3.0.4.0.1.7.2.7.3.7.4.7.5.1.5.2.5.3.5.4.5.5.5.6,].2: [
      0.0.0.1.1.0.2.0.3.0.4.0.5.0.5.1.5.2.5.3.4.3.3.3.2.3.2.4.1.4.1.5.0.5.0.6.0.7.1.7.2.7.3.7.4.7.5.7.5.6,]};Copy the code

For details on how to draw the letter coordinates, see the following figure, using the number 2 and the letter Y as examples:

The array is divided into two bits, roughly drawing the following letter and number symbols according to the horizontal and vertical positions.

Concrete drawing function

The specific implementation logic can be divided into 5๏ธ one function:

  • Initializes the particle text function
  • Update motion function
  • Draw content function
  • Looping animation executes the function
  • Random color generation function

Initializes the particle text function

  • Judgment loop indexiThe length oftextStringThe length of the inside.
  • Generate randomvelocityParameters.
  • According to thetextMatrixInitializes multiple particle objects at the location of the corresponding contents in.
  • listTextFills the generated particle object.
  • Check whether the index is filled by increasing. If the index is not filled, continue to fill.
function initText() {
    const i = textIndex;
    if (i >= 0 && i < textString.length) {
      const velocity = Math.random() * 0.25 + 1;
      const shift = { x: - (Math.random() + 2), y: - (Math.random() + 3)};const char = chars[textString[i]];
      const width = 80;
      const half = 6.5 * width;
      const left = textMatrix[i * 2] * width - half;
      const top = textMatrix[i * 2 + 1] * range * 1.2 - range * 2.4;
      for (let j = 0; j < fireNumber * char.length * 0.25; j++) {
        const rand = Math.floor(Math.random() * char.length * 0.5);
        const x = char[rand * 2] + shift.x;
        const y = char[rand * 2 + 1] + shift.y;
        const text = {
          x: center.x + left * 0.9.y: center.y + top,
          left: center.x + left,
          size: Math.random() + 0.5.fill: randColor(),
          vx: x * (velocity + (Math.random() - 0.5) * 0.5),
          vy: y * (velocity + (Math.random() - 0.5) * 0.5),
          ay: 0.08.alpha: 1.life: Math.round((Math.random() * range) / 2) + range / 1.5}; text.base = {life: text.life,
          size: text.size,
        };
        text.direct = (text.left - text.x) * 0.08; listText.push(text); }}if (++textIndex < textString.length) {
      setTimeout(initText, 10); }}Copy the code

Update motion function

  • cyclelistTextParticle animation object.
  • Updates the movement, life cycle, and size of each item in the array.
  • Each life cycle decreases.
  • Check whether the life cycle ends and clear the item if so.
  • Update the particle text function
function update() {
    // Update the listText movement
    for (let i = listText.length - 1; i >= 0; i--) {
      const text = listText[i];
      text.vx *= 0.9;
      text.vy *= 0.9;
      text.direct *= 0.9;
      text.x += text.vx + text.direct;
      text.y += text.vy;
      text.vy += text.ay;
      text.alpha = text.life / text.base.life;
      text.size = text.alpha * text.base.size;
      text.alpha = text.alpha > 0.6 ? 1 : text.alpha;
      // Lifecycle decrement
      text.life--;
      if (text.life <= 0) {
        listText.splice(i, 1);
      }
    }

    initText();
}
Copy the code

Draw content function

  • Clear the canvas before each drawing.
  • Set the new image drawing target image specific properties.
    • specificglobalCompositeOperationMay refer toCanvas globalCompositeOperation propertiesContent to learn.
  • Follow the initial drawingcanvasTo draw.
function draw() {
    // Clear before drawing
    ctx.globalCompositeOperation = "source-over";
    ctx.globalAlpha = 0.2;
    ctx.fillStyle = "# 000";
    ctx.fillRect(0.0, canvas.width, canvas.height);

    // Set the new image drawing target image specific properties
    ctx.globalCompositeOperation = "screen";

    // Draw: HAPPY NEW YEAR 2020!
    for (let i = 0; i < listText.length; i++) {
      const text = listText[i];
      ctx.globalAlpha = text.alpha;
      ctx.fillStyle = text.fill;
      ctx.fillRect(
        text.x - text.size,
        text.y - text.size,
        text.size * 2,
        text.size * 2); }}Copy the code

Looping animation executes the function

  • userequestAnimationFrameMethod executes a loop function.
    • specificrequestAnimationFrameMay refer towindow.requestAnimationFrameContent to learn.
(function loop() { requestAnimationFrame(loop); update(); draw(); }) ();Copy the code

Random color generation function

The last function is actually simpler, encapsulating a common method of randomly generating RGB colors for each node in order to generate a color.

function randColor() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    const color = `rgb(${r}.${g}.${b}) `;
    return color;
}
Copy the code

conclusion

This is the end of all the code content, because time is limited, not line by line analysis, you can copy the above code snippets for actual preview and modification.

Have better idea and train of thought also welcome everybody to leave a message in the comment area, code word is not easy, see the friends if must I write the content of you have a little inspiration, I hope not to spare praise, your encouragement is my writing power!

Happy New Year to you in advance here! ๐Ÿ”ฅ

I wish you all:

Work smoothly, good health, all the best, happiness!

๐Ÿงจ Happy New Year, ๐Ÿฏ!