Languages
[Edit]
EN

JavaScript - calculate the center of gravity of the elements

15 points
Created by:
sarah_ldp
1480

In this article, we would like to show how to calculate the center of gravity (middle point) of the elements using JavaScript.

Center of gravity of the elements calculated in JavaScript.
Center of gravity of the elements calculated in JavaScript.

Quick solution:

function caculateMiddlePoint(elements) {
	var sumX = 0;
	var sumY = 0;

	for (var i = 0; i < elements.length; ++i) {
		var element = elements[i];

		var middleX = element.offsetLeft + 0.5 * element.offsetWidth;
		var middleY = element.offsetTop +  0.5 * element.offsetHeight;

		sumX += middleX;
		sumY += middleY;
	}

	return {
		x: sumX / elements.length,
		y: sumY / elements.length
	};
}

 

Practical example

To use above caculateMiddlePoint() function it is necessary to provide elements as argument. 

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    body {
    	height: 300px;
    }

    div.box {
        position: fixed;
    }

    #box-1 {
        left: 70px; top: 70px; background: #00c700; width: 120px; height: 54px;
    }

    #box-2{
        left: 300px; top: 50px; background: yellow; width: 138px; height: 162px;
    }

    #box-3{
        left: 30px; top: 250px; background: #3879C8; width: 300px; height: 30px;
    }

  </style>
</head>
<body>
  <div id="box-1" class="box">Box 1</div>
  <div id="box-2" class="box">Box 2</div>
  <div id="box-3" class="box">Box 3</div>
  <script>

 	function caculateMiddlePoint(elements) {
    	var sumX = 0;
        var sumY = 0;

        for (var i = 0; i < elements.length; ++i) {
          var element = elements[i];

          var middleX = element.offsetLeft + 0.5 * element.offsetWidth;
          var middleY = element.offsetTop +  0.5 * element.offsetHeight;

          sumX += middleX;
          sumY += middleY;
        }

      	return {
        	x: sumX / elements.length,
          	y: sumY / elements.length
        };
    }
    
    
    // Usage example:
    
    var boxElements = document.querySelectorAll('.box');
    var middlePoint = caculateMiddlePoint(boxElements);
    
    console.log('x: ' + middlePoint.x + ', y: ' + middlePoint.y);

  </script>
</body>
</html>
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join