preface

As the saying goes: Laba is the year. Laba festival after the Spring Festival has stepped on the hot wheels to chase! Are you looking forward to the Spring Festival this year?

New Year’s Eve and Spring Festival are the most important festivals in a year, and they are also wonderful days for family reunion. Recalling the past Spring Festival, Xiao Bao can not help but have a myriad of thoughts, including happiness, happiness, yearning and bitterness. The time of Spring Festival is short but eternal, deeply engraved in the sea of xiao Bao’s memories.

Don’t know what you remember New Year will be like? Next, let’s take a look at xiao Bao’s New Year’s memories with several key words animation.

Welcome to comment in the comments section, share your New Year’s memories keyword or keyword animation, we come together to understand or guess your New Year’s memories, like + comments the most digging friends packet will send him around the nuggets.

tool

Before sharing the case play and implementation, we first provide a few tools for you to customize your New Year memories.

  • Emoticon text website: you can go to the website to select the emoticon text you want (link provider: Spring guy)
  • ScreenToGif: You can use ScreenToGif to record your unforgettable New Year memories. Tools are relatively simple and crude to use.

As for screen recording, Xiao Bao was originally expected to realize the function of generating GIF, but found a lot of schemes, but the implementation effect was poor. In the future, Xiao Bao will continue to push forward the research in this aspect, and will continue to update the follow-up research if there is progress.

play

Experience address: customize your exclusive New Year memories

The gameplay is very simple, with a few things to watch out for:

  • Keywords are entered in the underlined position
  • Multiple keywords can be separated by Spaces or commas in Chinese or English
  • Support Chinese and English, emoticons
  • Text as far as possible not too long, less than five words
  • After entering the keyword sequence, the Enter key starts the animation

Let’s take a look at Xiao Bao’s Spring Festival memories.

childhood

Childhood have parcel some far away, that s not rich material life, spiritual life is scarce, but to hold packets was simple, climbed mountains, climbing sea, in dungeons, made countless memories engraved on packet, castle peak, neighbour, river, partner, simple to create endless wonderful life.

On New Year’s eve

The era of the year is full of flavor, New Year’s Eve package of three, eating dumplings, watching the Spring Festival Gala, like fire, the first zero, moonlight bridge, firecrackers sound, red envelope drum. Key words: 👨👩👦,🥟,📺,👏, 🥟,📺, 👨👩👦, 👨👩👦

Spring Festival

The Spring Festival day is more fulfilling, a family of three, get up at six o ‘clock, red lanterns, seven o ‘clock New Year’s call, walk home string lane, some people, candy peanuts, happy at large. Evolved into key words: 👨👩👦,🕕,🏮,🕖, 🕕, 👨👩👦, 👨👩👦, 👨👩👦, 👨👩👦, 👨👩👦, 👨👩👦, 👨👩👦,🕕, 👨👩👦

youth

The following part of the expression keywords will not be interpreted, you can guess, send in the comments, the closest will be sent out around the Nuggets

Key words: 👨👨👧👦,🥟,📺,🕛, square,🥟, 👨👨👧👦, 👨👨👧👦

epidemic

To tell the truth, with the growth of age, material life and spiritual life are developing rapidly, the fickle atmosphere of the society is getting stronger and stronger, and the flavor of The New Year is getting weaker and weaker. However, the year of the epidemic will become the eternal memory of the packet. The flavor of the New Year may be weaker, but the flavor of the New Year is stronger and stronger.

Key words: 👨👨👧👦,📺,🦠,🛌, 📺, 👨👨👧👦, 👨👨👧👦, 👨👨👧👦

Code implementation

Particle effect packet has been implemented many times, so the simple part of the packet will not do a detailed explanation, the core of the animation switch part.

Creating a particle class

Particle mainly includes particle random position, particle target position, particle color and particle radius. In this project, particle radius is uniformly set as 2.

class Particle {
  constructor({ x = 0, y = 0, tx = 0, ty = 0, radius = 2, color = "#F00000" }) {
    // The current coordinates are randomly generated
    this.x = particle.x;
    this.y = y;
    // Target point coordinates (sub-canvas original particle coordinates)
    this.tx = tx;
    this.ty = ty;
    this.radius = 2;
    this.color = color;
  }
 // Particle rendering
  draw(ctx) {
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.fillStyle = this.color;
    ctx.beginPath();
    // Draw a circle
    ctx.arc(0.0.this.radius, 0.Math.PI * 2.true);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
    return this; }}Copy the code

Extracting pixel information

Create subcanvas and draw text

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const viewWidth = window.innerWidth * 0.5;
const viewHeight = window.innerHeight * 0.5;

canvas.width = viewWidth;
canvas.height = viewHeight;
if (typeof target === "string") {
// Draw text
// Ensure that long text is fully displayed on PC and mobile
ctx.font = `${
      target.length < 3 ? textWidth : (textWidth * 3)/(1 + target.length)
    }px bold`;
ctx.fillStyle = colorList[rand(0, colorList.length)];
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillText(target, viewWidth / 2, viewHeight / 2);
  }

Copy the code

Get pixel data

getImageData

  • Syntax ctx.getImageData(sx, sy, sw, sh);

  • parameter

    • sx, sy: To extract the upper left corner of the imagex ycoordinates
    • sw, sh: To extract the width and height of the image
  • The return value

    Returns an ImageData object that copies the pixels of the specified image region. For each pixel in the image, RGBA quadrangles are stored separately, and all pixel numbers are stored as a one-dimensional array in the data property (each pixel is composed of four RGBA values, so you need to multiply by 4 each time to jump to the next pixel).

const { data, width, height } = ctx.getImageData(0.0, viewWidth, viewHeight);
Copy the code

Extract the pixel point of the particle to be drawn

Here’s an explanationintervalAnd why is it possible to control the number of pixels?

GetImageData returns all pixels of the extracted canvas. If all particles with radius 2 are drawn without filtering, on the one hand, the particles will overlap. On the other hand, due to the progress of the display screen, there are too many pixels, and the generated particles will be too many. The movement of too many particles will consume a huge amount of rendering performance, and the rendering effect will be very stuck, which is really a bad strategy.

So we need to find a way to adapt to a variety of displays, but also render the right number of particles, so how do we deal with getImageData return data that?

They select the width and height of the canvas as the selection baseline. Interval is the selection interval. The larger the interval value is, the larger the interval is, so the fewer pixels are selected in each line.

Now, how do I locate this pixel? GetImageData returns data that reads pixels in rows, each pixel held in four array bits. If we use width and height as a baseline, y * canvas width + x gives the pixel position, and position 4 calculates the index position in the ImageData array.

Interval controls the number of pixels. The larger the value, the fewer pixels are returned
  const pixeles = [];
  // Iterate over the pixel data and use interval to reduce the number of pixels taken
  for (let x = 0; x < width; x += interval) {
    for (let y = 0; y < height; y += interval) {
      const pos = (y * width + x) * 4; 
      // Extract only rGBA pixels with transparency greater than 0.5, i.e. Aplha > 128
      if (data[pos + 3] > 128) {
        pixeles.push({
          x,
          y,
          rgba: [data[pos], data[pos + 1], data[pos + 2], data[pos + 3]],}); }}}return pixeles;
}
Copy the code

Draw the particles

Add particles according to the pixel, and the target position and color of particles are provided by the pixel.

function createParticles({ text, radius, interval }) {
  const pixeles = getWordPxInfo(text, interval);
  return pixeles.map((particle) = > {
    return new Particle({
      x: Math.random() * (50 + window.innerWidth * 0.5) - 50.y: Math.random() * (50 + window.innerHeight * 0.5) - 50.tx: particle.x,
      ty: particle.y,
      radius: particle.raduis,
      color: particle.rgba,
    });
  });
}

Copy the code

Text switch

The case achieves the switching effect of text, so it is necessary to determine whether all particles reach the target after each update of particle position.

Each particle has the FINISHED property, which defaults to true. After the finished particle movement is complete, change the FINISHED value to true

Because each particle has the FINISHED property, you can use Filter to filter out all particles whose finished property is True. If the number of particles in the finished property is equal to the total number of particles, the current text animation ends and the next text is switched to.

// The parameters are the array of particles and the next text animation callback
function drawFrame(particles, finished) {
  // Enable particle render animation
  const timer = window.requestAnimationFrame(() = > {
    drawFrame(particles, finished);
  });
  ctx.clearRect(0.0, canvas.width, canvas.height);
  // Set the ease coefficient to 0.09
  const easing = 0.09;
  const finishedParticles = particles.filter((particle) = > {
    // The distance between the current coordinate and the target point
    const dx = particle.tx - particle.x;
    const dy = particle.ty - particle.y;
    // Particle moving speed
    let vx = dx * easing;
    let vy = dy * easing;

    // Determine whether the current particle is animated
    if (Math.abs(dx) < 0.1 && Math.abs(dy) < 0.1) {
      // The position of the finished animation will not change
      particle.finished = true;
      particle.x = particle.tx;
      particle.y = particle.ty;
    } else {
      // Continue to update particle positions while animations are incomplete
      particle.x += vx;
      particle.y += vy;
    }
    // Draw the particle's new position
    particle.draw(ctx);
    // Determine the number of particles that have completed the motion
    return particle.finished;
  });

  if (finishedParticles.length === particles.length) {
    // All particles move to the end of the current animation
    window.cancelAnimationFrame(timer);
    // Start the next text callback
    finished && finished();
  }
  return particles;
}

Copy the code

Animation switch function loop

The drawFrame function takes an array of particles and a callback function for the next text. The loop function receives the array of incoming text and passes the drawFrame to the generated particle for each text

function loop(words, i = 0) {
  return drawFrame(
    // Generate particles
    createParticles({ text: words[i], radius: 2.interval: 5 }),
    // Next text
    () = > {
      i++;
      // hack the empty text
      if (i < words.length && words[i].length > 0) { loop(words, i); }}); }Copy the code

Gifts in the year of the Tiger

To tell you the truth, since October in nuggets began to write, just entered 2022, Xiao Bao successfully registered LV4, xiao Bao’s own cognition is particularly clear, xiao Bao needs rapid progress in order to qualify as an excellent author. But I really appreciate the support of the big guys. I made a lot of new friends in the Nuggets side. I hope our friendship will last forever. In addition, I also want to thank the lovely operators of the Nuggets community, who are responsible and down-to-earth, so that xiao Bao, an old writer, can regain enthusiasm and regain the original heart. I hope to grow up and make progress together with the Nuggets in the New Year.

In the past six months, I collected a lot of wool from the community, some of which I gave to my friends, and some of which I gave to the most familiar strangers of gold diggers. I hope I will be more and more familiar with them in the future.

  1. Package reserved two groups of keywords, guess the most appropriate digging friends, the package will be sent around the nuggets
  2. Share your New Year’s memories (recorded GIFs or keywords), get the most likes and comments after digging friends, small bag will also send a gold nuggets
  3. I haven’t come up with other awards yet. If I come up with other awards later, I will add them dynamically

Source warehouse

Source address: custom your exclusive New Year memories

Experience address: customize your exclusive New Year memories

If you feel helpful, don’t forget to give the small bag a ⭐.

Past wonderful articles

  • Cow guest latest front-end JS written test 100 questions
  • The latest front end of the interview questions summary (including analysis)
  • CSS to achieve a free flying bird 🐦
  • Grab the latest front end test five hundred data analysis JS interview hot spots
  • Happy cat stroking for VSCode and website adoptive cats
  • Native JavaScript soul Test (1), how much can you answer?
  • A thorough understanding of prototypes and prototype chains in JavaScript
  • Complete understanding of EventLoop in JavaScript
  • “2W word big chapter 38 interview questions” completely clear JS this pointing to the problem

After the language

Guys, if you find this article helpful, give a like to 👍 or follow ➕ to support me.

In addition, if this article has a question, or do not understand part of the article, you can reply to me in the comment section, we come to discuss, learn together, progress together!

End the epidemic as soon as possible

Peace on earth