Pull to refresh

Анимация на JS: движение по окружности

Небольшая статья о том, как двигать объект по окружности на JavaScript:

Используем( необходимое из математики):
— полярную систему координат
— функции Math.cos, Math.sin, Math.Pi
— нахождения угла: alpha = const * pi / 180

1. Определим на css/html «место событий»:

body {
	background:#000000;
}
.css {
	position: absolute;
	background:#6495c4;
	width:30px;
	height:30px;
	left: 70px;
	top: 40px;
	border: 3px solid #fff;
	cursor: pointer;
	    border-radius: 19px;
	   -webkit-border-radius: 19px;
	   -moz-border-radius: 19px;

}
#round {
	position: absolute; 
	left: 50%;
	margin-left: -250px; 
	top: 100px; 
	width: 500px; 
	height: 500px;
	border: 5px solid #6495c4;
	    border-radius: 250px;
	   -webkit-border-radius: 250px;
	   -moz-border-radius: 250px;
	
}

   <div id="round">
       <div class="css" onClick="animation({}, this);"></div> 
       <div class="css" onClick="animation({}, this);"></div>
       <div class="css" onClick="animation({}, this);"></div>
    </div>


2. Теперь будем двигать их по окружности:

function animation(args, elem) { // некоторые аргументы определим на будущее
	var $ = {
		radius  :     250, // радиус окружности 
		speed   :     20 // скорость/задержка ( в js это мс, например 10 мс = 100 кадров в секунду)
	}
	var f = 0;
	var s = 2 * Math.PI / 180; //Вычислим угол
	setInterval(function() { // функция движения 
		f += s; // приращение аргумента
		  elem.style.left =  235 + $.radius * Math.sin(f)  + 'px'; // меняем координаты элемента, подобно тому как мы это делали в школе в декартовой системе координат. Правда, в данном случае используется полярная система координат, изменяя угол
		  elem.style.top =   235 + $.radius * Math.cos(f) + 'px';
	}, $.speed)
}

Вот что вышло:

image
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.