Home >Web Front-end >CSS Tutorial >How to Rotate Multiple Objects Around a Circle Using CSS and jQuery?

How to Rotate Multiple Objects Around a Circle Using CSS and jQuery?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-13 14:53:10834browse

How to Rotate Multiple Objects Around a Circle Using CSS and jQuery?

Rotate Multiple Objects Around a Circle Using CSS

While rotating a single object around a circle can be achieved with CSS, the challenge arises when you want to rotate multiple objects simultaneously. Here's a detailed solution that will guide you through this process:

The solution utilizes jQuery, which is a powerful JavaScript library that simplifies DOM manipulation and animation. It allows you to rotate multiple objects around a circle regardless of their number.

var radius = 100; // adjust to move out items in and out 
var fields = $('.item'),
  container = $('#container'),
  width = container.width(),
  height = container.height();
var angle = 0,
  step = (2 * Math.PI) / fields.length;
fields.each(function() {
  var x = Math.round(width / 2 + radius * Math.cos(angle) - $(this).width() / 2);
  var y = Math.round(height / 2 + radius * Math.sin(angle) - $(this).height() / 2);
  if (window.console) {
    console.log($(this).text(), x, y);
  }
  $(this).css({
    left: x + 'px',
    top: y + 'px'
  });
  angle += step;
});

This jQuery code calculates the position of each object based on the radius of the circle and the number of objects. It sets the left and top positions of each object to align it around the perimeter of the circle.

To complete the animation, you can add the following CSS rules:

body {
  padding: 2em;
}
#container {
  width: 200px;
  height: 200px;
  margin: 10px auto;
  border: 1px solid #000;
  position: relative;
  border-radius: 50%;
  animation: spin 10s linear infinite;
}
.item {
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
  position: absolute;
  background: #f00;
  animation: spin 10s linear infinite reverse;
}
@keyframes spin {
  100% {
    transform: rotate(1turn);
  }
}

These rules create a container with a circular border, and each object rotates around the container in opposite directions. By adjusting the radius variable, you can control the distance of the objects from the center of the circle.

By combining jQuery and CSS, you can easily rotate multiple objects around a circle using CSS and achieve the desired animation effect.

The above is the detailed content of How to Rotate Multiple Objects Around a Circle Using CSS and jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn