0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Angular で parallax 実装してみた

Last updated at Posted at 2021-06-21

Angular + parallax.js の組み合わせに関する記事が少なかったので、書いてみます。

完成イメージ

パララックスにもいくつか種類があるみたいですが、この記事は
マウスの hover に合わせて背景がズレるやつを Angular で実装する例です

Jun-21-2021 22-06-47.gif

参考にしたサイト

基本的には、下記のサイトに答えが載っているのだが、改めてここに記す
How To Use parallax.js in Angular 2+(5.2.10) - Medium

下準備

すでに Angular のプロジェクトが存在しており、ParallaxComponent という名前のコンポーネントがあるものとして解説します。

手順1 parallax-js をインストール

npm i parallax-js

image.png

手順2 angular.json に parallax.js の参照を追加

angular.json
"scripts": [
  "./node_modules/parallax-js/dist/parallax.min.js"
]

image.png

手順3 require を使うので @types/node をインストール

これを参考に
angular 7(TypeScript 3.1.3)で名前 'require'が見つかりません

@types/node をインストール

npm i @types/node

image.png

tsconfig.app.json に "types":["node"] を追加

tsconfig.app.json
  "compilerOptions": {
    "types": [
      "node"
    ]

image.png

コンポーネント の編集

以下の ngAfterContentInit() 関数を追加

parallax.component.ts
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/

parallax.component.html
<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>
parallax.component.css
.container{
    background: url("../../assets/background.jpg") no-repeat;
    width: 100%;
    overflow: hidden;
}

image.png

まとめ

以上で
Angular11 で parallax.js を使うことができました
parallaxonhover-min.gif

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?