smooth animation
Smooth movement using sin wave
by uto usui
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenMax.min.js"></script>
<div class="target"></div>
SCSS
body {
transform-style: preserve-3d;
perspective: 500px;
}
.target {
width: 100px;
height: 100px;
background-color: lightgray;
transform-origin: 50% 50% 50%;
}
Babel + JSX
class smoothMove {
/**
*
* @param target {Object}
* @param speed {Number}
* @param wrapWidth {Number} デフォルトはウィンドウサイズ
* @param wrapHeight {Number} デフォルトはウィンドウサイズ
*/
constructor(target, speed = 2, wrapWidth = window.innerWidth, wrapHeight = window.innerHeight) {
this.target = target;
// 角度
this.angle = 0;
// スピード
this.speed = speed;
// 中心の座標
this.center = {
x: wrapWidth / 2 - this.target.width() / 2,
y: wrapHeight / 2 - this.target.height() / 2
};
// 動く範囲を円の半径で表現
// この倍の値(直径)が移動範囲になる
this.radius = window.innerHeight / 4;
return this;
}
/**
* ラジアンに変換する
* @param angle
* @returns {number}
*/
getRadian(angle) {
return angle * Math.PI / 180;
}
/**
* 新しい範囲における現在の値を、現在の範囲を元に変換して返す
* map(a, b, c, d, e) aを範囲b-cから別の範囲d-eへ変換する
* @param value {Number}
* @param fromMin {Number} 変換前の最小
* @param fromMax {Number} 変換前の最大
* @param toMin {Number} 変換後の最小
* @param toMax {Number} 変換後の最大
*/
map(value, fromMin, fromMax, toMin, toMax) {
let result = 0;
result = (value <= fromMin)
? toMin : (value >= fromMax)
? toMax : (() => {
let ratio = (toMax - toMin) / (fromMax - fromMin);
return (value - fromMin) * ratio + toMin;
})();
return result;
}
/**
* アニメーションを始める
*/
play() {
let radian = this.getRadian(this.angle);
// Math.sin(radian)は-1から1までを正弦波で返す
// radiusをかけることでそれを半径とする円の範囲でアニメーション
// Math.sin(radian) * 範囲
let offsetX = Math.sin(radian) * this.radius;
let color = `hsla(${this.map(Math.sin(radian), -1, 1, 0, 360) / 2}, 70%, 70%, 1)`
TweenMax.set(this.target, {
x: this.center.x + offsetX,
y: this.center.y,
backgroundColor: color
});
// アニメーションで使用する角度を進める量
// つまり、速度
this.angle += this.speed;
requestAnimationFrame(() => {
this.play();
});
}
}
let anim = new...