Fifty lines of code to get the bomb screen effect

Preface

In recent years, the bullet curtain has slowly become popular. We can see the image of the barrage when we watch video or live broadcasting on the internet. Sometimes the content of the barrage is even more wonderful than the content of the video itself. I also like the marble curtain very much. It's common to brush a marble curtain at a wonderful spot. Just recently, I was relatively idle, so I wrote a Demo to show how to achieve the effect of the barrage. Deficiencies, please leave a comment.

Realization Principle

Project structure

The project structure is very simple, very standard html+css+js structure. Here we use a third-party jQuery library to help us achieve this barrage effect. If you are interested, you can try to use native js to achieve this function. After reading this article, I believe you can also easily use native js to achieve.

HTML and CSS file content

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Bullet Curtain Wall</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <div class="screen_container"></div>
    <div class="screen_toolbar">
        <input id="screenBulletText" type="text" placeholder="Please enter the content of the barrage"/>
        <button class="send">launch</button>
        <button class="clear">Close the barrage</button>
    </div>
</body>
<script src="./jquery-3.2.1.min.js"></script>
<script src="./main.js"></script>
</html>

Here the layout of our page is very simple, mainly divided into two divs:

  1. Di. screen_container serves as our barrage wall, where we will put the content of the barrage we launched.

  2. div.screen_toolbar contains an input box for entering the content of the projectile we need to launch, a launch button and a close button.

Another is the introduction of third-party libraries and our own css and js.

CSS

.screen_container{
    position: relative;
    width: 600px;
    height: 400px;
    margin: 30px auto;
    background: #000;
    overflow: hidden;
}
.screen_toolbar{
    width: 600px;
    margin: 20px auto;
    text-align: center;
}

CSS to slightly beautify our layout, here we do not set the style of our barrage.

HTML+CSS rendering

JS implementation

Overall Realization Principle of Ballistic Curtain

The realization principle of the barrage is very simple. We click the "Launch" button and generate a div to insert into the div.screen_container according to the content of the input barrage, and randomly initialize the position of the div we generated. In this way, we have a projectile curtain generated by ourselves, but at this time, the projectile curtain has not yet moved. We need to add a timing task to it, reduce the value of CSS attribute left of the projectile curtain, and then we can achieve the moving effect. Finally, when the curtain moves out of the curtain wall, destroy the curtain. The whole process of realizing the effect of the barrage is roughly like this, is it simple?

The effect of bullet curtain can be achieved by stages.

1. Generate the barrage according to the specified content, initialize its position and style, and insert it into div.screen_container.

function createScreenbullet(text) {
    var jqueryDom = $("<div class='bullet'>" + text + "</div>");
    var fontColor = "rgb(" + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random()) + ")";
    var fontSize = Math.floor((Math.random() + 1) * 24) + "px";
    var left = $(".screen_container").width() + "px";
    var top = Math.floor(Math.random() * 400) + "px";
    top = parseInt(top) > 352 ? "352px" : top;
    jqueryDom.css({
        "position": 'absolute',
        "color": fontColor,
        "font-size": fontSize,
        "left": left,
        "top": top
    });
    $(".screen_container").append(jqueryDom);
    return jqueryDom;
}

Here we need to pay attention to the following points:

  1. Here we are based on the location of the parent div.screen_container, where our bullet curtain value left value is the width of div.screen_container (that is, each bullet curtain moves from the right to the left of the bullet curtain wall).

  2. With regard to the top value of the barrage, since our font size is set between 24px and 48px, our maximum top value is 352px (that is, the height of div.screen_container minus 48).

  3. Don't forget to set the position attribute for each barrage with the value "absolute"“

2. Add a timing task to the barrage.

function addInterval(jqueryDom) {
    var left = jqueryDom.offset().left - $(".screen_container").offset().left;
    var timer = setInterval(function () {
        left--;
        jqueryDom.css("left", left + "px");
        if (jqueryDom.offset().left + jqueryDom.width() < $(".screen_container").offset().left) {
            jqueryDom.remove();
            clearInterval(timer);
        }
    }, 10);
    timers.push(timer);
}

Here we need to pay attention to the following points:

  1. Gets the left value of the css attribute of the specified barrage. In addition to the above method, it can also be obtained by parseInt(jqueryDom.css("left") or parseFloat(jqueryDom.css("left").

  2. Judgment of the critical point for eliminating the barrage. Judging whether the barrage is out of bounds depends on whether the right side of the barrage is out of bounds. Here we have two ways of judging. The first is based on the leftmost side of the viewer. The value of the distance between the bomb curtain and the left side of the viewer plus the width of the bomb curtain itself is less than the distance between the bomb curtain wall and the left side of the viewer is the exit. The second is parseFloat (jqueryDom. css ("right")> 600 to determine whether the right value of the css attribute of the bomb curtain is greater than 600 (that is, the width of the bomb curtain wall).
    3.timers is a global timed task queue we set up.

3. Monitor "Send" button

$(".send").on("click", function () {
    // Creating a Barrage Curtain
    var jqueryDom = createScreenbullet($("#screenBulletText").val());
    // Add Timing Tasks
    addInterval(jqueryDom);
});

If we want to experience better, we can add an Enter button to listen.

$("#screenBulletText").on("keydown", function (event) {
    if (event.keyCode == 13) {
        // Creating a Barrage Curtain
        var jqueryDom = createScreenbullet($("#screenBulletText").val());
        // Add timer
        addInterval(jqueryDom);
    }
});

4. Close the Barrage Function

The first one: transparency control of projectile curtain

The following isShow is a global variable to record the state of the barrage.

$(".clear").on("click", function () {
    if (isShow) {
        $(".bullet").css("opacity", 0);
        isShow = false;
    } else {
        $(".bullet").css("opacity", 1);
        isShow = true;
    }
});

The advantage is that the scheduled tasks will not end. When we close the barrage, we actually make it invisible.

The second is to terminate the timing task directly and remove all the barrages.

The following timers is a global timed task queue we set up.

$(".clear").on("click", function () {
    for(var i=0;i<timers.length;i++){
        clearInterval(timers[i]);
    };
    $(".bullet").remove();
});

This is a simple and rude way to end all the timing tasks and remove all the barrages.

The above two kinds, you can choose according to your own needs.

Final full version of JS code

// Barrage timer
var timers = [];
// Controlling the Explicit and Implicit Variables of Barrage
var isShow = true;
// Listen for the Send Button
$(".send").on("click", function () {
    // Creating a Barrage Curtain
    var jqueryDom = createScreenbullet($("#screenBulletText").val());
    // Add Timing Tasks
    addInterval(jqueryDom);
});
// Monitor Close Barrage Button
$(".clear").on("click", function () {
    if (isShow) {
        $(".bullet").css("opacity", 0);
        isShow = false;
    } else {
        $(".bullet").css("opacity", 1);
        isShow = true;
    }   
});
// Build a new barrage
function createScreenbullet(text) {
    var jqueryDom = $("<div class='bullet'>" + text + "</div>");
    var fontColor = "rgb(" + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random() * 256) + "," + Math.floor(Math.random()) + ")";
    var fontSize = Math.floor((Math.random() + 1) * 24) + "px";
    var left = $(".screen_container").width() + "px";
    var top = Math.floor(Math.random() * 400) + "px";
    top = parseInt(top) > 352 ? "352px" : top;
    jqueryDom.css({
        "position": 'absolute',
        "color": fontColor,
        "font-size": fontSize,
        "left": left,
        "top": top
    });
    $(".screen_container").append(jqueryDom);
    return jqueryDom;
}
// Adding Timing Tasks to the Barrage
function addInterval(jqueryDom) {
    var left = jqueryDom.offset().left - $(".screen_container").offset().left;
    var timer = setInterval(function () {
        left--;
        jqueryDom.css("left", left + "px");
        if (jqueryDom.offset().left + jqueryDom.width() < $(".screen_container").offset().left) {
            jqueryDom.remove();
            clearInterval(timer);
        }
    }, 10);
    timers.push(timer);
}

Final effect

Brush yourself 666666!

Keywords: Javascript Attribute JQuery IE less

Added by cgchris99 on Tue, 18 Jun 2019 23:42:54 +0300