Angular + parallax.js の組み合わせに関する記事が少なかったので、書いてみます。
完成イメージ
パララックスにもいくつか種類があるみたいですが、この記事は
マウスの hover に合わせて背景がズレるやつを Angular で実装する例です
参考にしたサイト
基本的には、下記のサイトに答えが載っているのだが、改めてここに記す
How To Use parallax.js in Angular 2+(5.2.10) - Medium
下準備
すでに Angular のプロジェクトが存在しており、ParallaxComponent
という名前のコンポーネントがあるものとして解説します。
手順1 parallax-js をインストール
npm i parallax-js
手順2 angular.json に parallax.js の参照を追加
"scripts": [
"./node_modules/parallax-js/dist/parallax.min.js"
]
手順3 require を使うので @types/node をインストール
これを参考に
angular 7(TypeScript 3.1.3)で名前 'require'が見つかりません
@types/node をインストール
npm i @types/node
tsconfig.app.json に "types":["node"] を追加
"compilerOptions": {
"types": [
"node"
]
コンポーネント の編集
以下の ngAfterContentInit()
関数を追加
import { Component } from '@angular/core';
@Component({
selector: 'app-parallax',
templateUrl: './parallax.component.html',
styleUrls: ['./parallax.component.scss']
})
export class ParallaxComponent {
constructor() { }
ngAfterContentInit() {
const Parallax = require('parallax-js')
const scene = document.getElementById('scene');
const parallaxInstance = new Parallax(scene, {
relativeInput: true,
haverOnly: true
});
}
}
html、css はこんな感じで, container
に背景画像を css で設定する
参考サイト
https://csspoint101.com/parallax-on-hover-effect-using-parallax-js/
<div id="container" class="container">
<div id="scene" class="scene">
<div data-depth="1.00"><img src="../../assets/astronaut.png"></div>
<div data-depth="0.60"><img src="../../assets/Neptune.png"></div>
<div data-depth="0.40"><img src="../../assets/Mars.png"></div>
<div data-depth="0.80"><img src="../../assets/rocket.png"></div>
</div>
</div>
.container{
background: url("../../assets/background.jpg") no-repeat;
width: 100%;
overflow: hidden;
}