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

Detailed explanation of MySQL master-slave replication and read-write separation

Article mind map Why use master-slave replication...

9 ways to show and hide CSS elements

In web page production, displaying and hiding ele...

JS array deduplication details

Table of contents 1 Test Cases 2 JS array dedupli...

Introduction to the three essential logs for MySQL database interviews

Table of contents 1. redo log (transaction log of...

Use of Linux date command

1. Command Introduction The date command is used ...

9 Practical CSS Properties Web Front-end Developers Must Know

1. Rounded Corners Today's web designs are con...

CentOS6.8 uses cmake to install MySQL5.7.18

Referring to the online information, I used cmake...

Complete steps to quickly configure HugePages under Linux system

Preface Regarding HugePages and Oracle database o...

How to configure multiple projects with the same domain name in Nginx

There are two ways to configure multiple projects...

How to obtain a permanent free SSL certificate from Let's Encrypt in Docker

1. Cause The official cerbot is too annoying. It ...

Customization Method of Linux Peripheral File System

Preface Generally speaking, when we talk about Li...

5 tips for writing CSS to make your style more standardized

1. Arrange CSS in alphabetical order Not in alphab...

How to use TypeScript in Vue

introduction In recent years, the call for TypeSc...