Native js to realize bouncing ball

Native js to realize bouncing ball

On a whim, I wrote a case study of a small ball bouncing back and forth for your reference. The specific content is as follows

The main method is to use the margin-left / top value for displacement. Of course, you can also use positioning to do it.

The ones used in this case are:

  • DOM element acquisition
  • DOM style manipulation
  • .offsetWidth Gets the element width
  • .offsetHeight Get the element height
  • setInterval() Timer

On the code

Use native js as a whole

<style> //style style* {
            margin: 0;
            padding: 0;
        }

        #box {
            width: 500px;
            height: 600px;
            background-color: #eee;
            box-shadow: 0 0 10px 0 #000;
            margin: auto;
            overflow: hidden;
            position: relative;
            margin-top: 50px;
        }

        #box div {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: #fff;
            position: absolute;
        }
    </style>
    <body>
    <div id="box">
        <div id="cir"></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>
</body>
<script>
var box = document.getElementById("box");
var cir = document.getElementById("cir")
var cirs = box.querySelectorAll("div");
collMove(box, cir, 6);
collMove(box, cirs[1], 7);
collMove(box, cirs[2], 8);
collMove(box, cirs[3], 9);
collMove(box, cirs[4], 10);
collMove(box, cirs[5], 10);
collMove(box, cirs[6], 11);
/**
 * The element pops up when it encounters a boundary* Change the element color while popping up* @param {Container to get} box 
 * @param {get the bounce element in the container} cir 
 * @param {bounce speed} speed 
 */
function collMove(box, cir, speed) { //Method encapsulation var oDiv = box; //Get the container var oCir = cir; //Get the element in the container var xMax = oDiv.offsetWidth - oCir.offsetWidth; //Maximum X-axis boundary of the container var yMax = oDiv.offsetHeight - oCir.offsetHeight; //Maximum Y-axis boundary of the container var motionX = 0; //Element X-axis coordinate initialization var motionY = 0; //Element Y-axis coordinate initialization (() => {
        var speedX = speed; //x-axis offset var speedY = speed; //y-axis offset setInterval(() => {
            motionX += speedX; //Perform X-axis offsetmotionY += speedY; //Perform y-axis offsetif (motionX >= xMax) { //Check if it hits the right boundary of the X-axismotionX = xMax; //When hitting the boundary, set the X-axis coordinate to the maximum right boundary of the x-axisspeedX = -speedX; //Reverse the x-axis offsetrandColor(oCir); //Change color} else if (motionX <= 0) { //Check if it hits the left boundary of the X-axismotionX = 0; //When hitting the boundary, set the X-axis coordinate to 0, i.e. the initial position of the left boundaryspeedX = -speedX; //Reverse the X-axis offset againrandColor(oCir); //The same goes for the upper and lower boundary detection below}
            if (motionY >= yMax) {
                motionY = yMax;
                speedY = -speedY
                randColor(oCir);
            } else if (motionY <= 0) {
                motionY = 0;
                speedY = -speedY;
                randColor(oCir);
            }
            oCir.style.marginLeft = motionX + "px"; //Set the element's X-axis coordinate oCir.style.marginTop = motionY + "px"; //Set the element's Y-axis coordinate }, 10);
    })();

    function randColor(obj) { //Encapsulate a random color, change the color and call directly var op = Math.random() * 7 + 3;

        function color() {
            return Math.floor(Math.random() * 256);
        }
        return obj.style.backgroundColor = `rgba(${color()},${color()},${color()},${op})`;
    }
}
</script>

The most important thing in the whole method is to understand the detection and judgment of element position and container boundaries . Once you understand this part, the rest will be very simple.
Here’s a tip: Don’t set the container to a standard square , otherwise the ball will only be able to bounce back and forth from the upper left corner to the lower right corner due to the angle.
The entire method is encapsulated. When you need it, you only need to copy the entire method or link it in and then directly use the method name according to the corresponding parameters. Call one element at a time. If you are not too busy, you can directly write a for loop to call it repeatedly.

Throw a brick:

for(var i = 1 ; i<=10;i++){
 collMove(box,cirs[i],i);
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JavaScript+canvas realizes the jumping ball in the frame
  • JavaScript combined with Canvas to draw sports balls
  • JavaScript canvas implements moving the ball following the mouse
  • Native js to realize moving ball (collision detection)
  • js realizes the movement of the ball in the specified area of ​​the page
  • Use js to realize the free movement code of the ball
  • js realizes a small ball that follows the mouse movement
  • JavaScript realizes the movement of a ball along a sine curve
  • P5.js Getting Started Tutorial: Ball Animation Example Code
  • Native js realizes the bouncing ball effect

<<:  MySQL multi-table query detailed explanation

>>:  How to solve the error of PyCurl under Linux

Recommend

How to use cutecom for serial communication in Ubuntu virtual machine

Using cutecom for serial communication in Ubuntu ...

React uses routing to redirect to the login interface

In the previous article, after configuring the we...

How to recover accidentally deleted messages files in Linux

If there are files that are being used by a proce...

MySQL 5.7.17 Compressed Version Installation Notes

This article shares the installation steps of MyS...

How to install git on linux

1. Introduction Git is a free, open source distri...

Example of how to implement underline effects using Css and JS

This article mainly describes two kinds of underl...

Complete steps to reset the root user password in mysql8

Preface Recently, many new colleagues have asked ...

Is it necessary to create a separate index for the MySQL partition field column?

Preface Everyone knows that the partition field m...

Solution to mysql error code 1064

If the words in the sql statement conflict with t...

JavaScript custom calendar effect

This article shares the specific code of JavaScri...

Pure CSS and Flutter realize breathing light effect respectively (example code)

Last time, a very studious fan asked if it was po...

Tips for implementing list loop scrolling based on jQuery (super simple)

I saw a good idea and recorded it. I have used jQ...

How to use partitioning to optimize MySQL data processing for billions of data

When MySQL queries tens of millions of data, most...

CSS border adds four corners implementation code

1.html <div class="loginbody"> &l...