background

A large screen project needs to display the data returned by the back end. The desired effect is as follows

plan

Using wordCloud2. js to achieve static data display, and then through the CSS animation, page flash effect

wordcloud2.js

Wordcloud2 can generate word clouds through Cavans or HTML tags

The installation

// npm
npm install wordcloud
// yarn
yarn add wordcloud
Copy the code

Simple to use

<! -- Using HTML tags --> 
<div id="word-cloud">

</div>

<! -- Use cavans tag --> 
<cavans id="word-cloud>
</cavans>
Copy the code
import WordCloud from 'wordcloud';
const list = [['A word cloud'.30], ['word cloud B'.28]].const $el = document.getElementById('word-cloud')
WordCloud($el, { list } );
Copy the code

Wordcloud can only display data. To animate text, we need to use wordCloud apis and CSS3 animate.

The idea is to group each word cloud first, assume that each group of data is 7, and then use CSS selector to set the color of the fixed position of each group of elements

.word-color:nth-child(7n + 1) {
  color: rgb(202.110.255);
}
.word-color:nth-child(7n + 2) {
  color: rgb(83.110.255);
}
.word-color:nth-child(7n + 3) {
  color: rgb(143.253.241);
}
.word-color:nth-child(7n + 4) {
  color: rgb(183.255.112);
}
.word-color:nth-child(7n + 5) {
  color: rgb(255.212.126);
}
.word-color:nth-child(7n + 6) {
  color: rgb(248.140.131);
}
.word-color:nth-child(7n + 7) {
  color: rgb(104.160.255);
}
Copy the code

Similarly, we set the animation effect for each group of elements, and use animation-delay to stagger the animation of words at different positions

@keyframes word {
  0% {
    opacity: 0.5;
  }
  3% {
    opacity: 1;
  }
  9% {
    opacity: 1;
  }
  12% {
    opacity: 0.5;
  }
  100% {
    opacity: 0.5; }}.word-animate {
  animation-name: word;
  animation-duration: 20s;
  animation-iteration-count: infinite;
  will-change: opacity;
  opacity: 0.5;
}

.word-animate:nth-child(7n + 1) {
  animation-delay: 0s;
}
.word-animate:nth-child(7n + 2) {
  animation-delay: 3s;
}
.word-animate:nth-child(7n + 3) {
  animation-delay: 6s;
}
.word-animate:nth-child(7n + 4) {
  animation-delay: 9s;
}
.word-animate:nth-child(7n + 5) {
  animation-delay: 12s;
}
.word-animate:nth-child(7n + 6) {
  animation-delay: 15s;
}
.word-animate:nth-child(7n + 7) {
  animation-delay: 18s;
}
Copy the code

In detail, since the word is expected to be displayed normally at the beginning, we will animate the element after wordCloud2 has generated the wordcloud.

// Listen for the execution end event
$el.addEventListener("wordcloudstop".function () {
  // Wait for 2s before adding the animation class, otherwise the normal display time is too short.
  setTimeout(() = > {
    let els = this.querySelectorAll(".word-color")
    Array.from(els).forEach((el) = > {
      el.classList.add("word-animate")})},2000)})Copy the code

The complete code