円周上に沿ってアニメーションさせてみる

円周上に沿って要素を移動させる処理を実装してみます。

サンプルコード

HTML

#roundが移動する円周、#circleが実際に移動する要素になります。

<div id="area">
	<div id="round"></div>
	<div id="circle"></div>
</div>

CSS

円周上のx座標とy座標を計算して、#circleのleftとtopを変更して移動させます。

#area {
	position: relative;
	width: 300px;
	height: 300px;
	margin: 50px auto;
}
#round {
	width: 300px;
	height: 300px;
	box-sizing: border-box;
	border: #000000 2px solid;
	border-radius: 150px;
}
#circle {
	position: absolute;
	top: 140px;
	left: 140px;
	width: 20px;
	height: 20px;
	border-radius: 10px;
	background: #E74C3C;
}

JavaScript

移動する要素(#circle)の軸になる座標が中心ではなく左上になるので、円の中心座標は実際の中心座標から移動する要素のサイズの半分を引いています。

// 演習場を移動する要素
var moveElement = document.getElementById('circle');
// 円の半径
var radius = 150;
// 円の中心座標
var centerX = 150 - 10;
var centerY = 150 - 10;
// 円の角度
var angle = 0;

// アニメーションの実行
setInterval(function() {
	circumference();
}, 20);

// アニメーションの処理
function circumference() {
	// 角度毎の円周上の座標を取得
	var moveX = Math.cos(Math.PI / 180 * angle) * radius + centerX;
	var moveY = Math.sin(Math.PI / 180 * angle) * radius + centerY;
	// 座標位置に移動
	moveElement.style.left = moveX + 'px';
	moveElement.style.top = moveY + 'px';

	if(angle < 360) {
		// 角度を1度増やす
		angle++;
	} else {
		// 角度を0に戻す
		angle = 0;
	}
}

円周上をアニメーションするデモページ
 

【参考サイト】

 

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年3月
 12
3456789
10111213141516
17181920212223
24252627282930
31