スクロールに応じて3Dモデルを回転させる

Ads

Result


表題の通りで、3Dモデル(サンプルでは.glbファイル)を、スクロールに同期させて回転させる、というもの。

3Dモデルを動かすにあたり、ARでお馴染みのmodel-vieweを使用する以外はバニラなコードとなっています。

javascript

const trackAnimationProgress = (animation, cb, precision = 5) => {
	let progress = 0;
	const updateValue = () => {
		if (animation && animation.currentTime) {
			let newProgress = animation.effect.getComputedTiming().progress * 1;
			if (animation.playState === "finished") newProgress = 1;
			newProgress = Math.max(0.0, Math.min(1.0, newProgress)).toFixed(precision);

			if (newProgress != progress) {
				progress = newProgress;
				cb(progress);
			}
		}
		requestAnimationFrame(updateValue);
	};
	requestAnimationFrame(updateValue);
}

const model = document.querySelector("model-viewer");
trackAnimationProgress(model.getAnimations()[0], (progress) => {
	model.orientation = `0deg 0deg ${progress * -360}deg`;
});

回転については、固定したい軸を0degにすればいいので、動かしたい軸は${progress * -360}degを指定するなどしてください。

3Dモデルは以下のように呼び出します。

html

<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.1.1/model-viewer.min.js"></script>
<model-viewer src="hogehoge.glb"></model-viewer>

下記で詳しく解説されています。

via

Synchronize videos, 3D-models, etc. to Scroll-Driven Animations

タイトルとURLをコピーしました