# distortion slider

with Three.js.

# DS-1

import * as THREE from 'three';
import {TweenMax} from 'gsap';

const vertex = `
  varying vec2 vUv;
  void main() {
    vUv = uv;
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  }
  `;

const fragmentDefault = `
  varying vec2 vUv;

  // images
  uniform sampler2D texture1;
  uniform sampler2D texture2;
  uniform sampler2D disp;

  uniform float dispPower; // 0 ~ 1
  uniform float intensity;

  void main() {
    vec2 uv = vUv;

    vec4 disp = texture2D(disp, uv);
    vec2 dispVec = vec2(disp.x, disp.y);

    // naname 1
    vec2 distPos1 = uv + (dispVec * intensity * dispPower);
    vec2 distPos2 = uv + (dispVec * -(intensity * (1.0 - dispPower)));

    vec4 _texture1 = texture2D(texture1, distPos1);
    vec4 _texture2 = texture2D(texture2, distPos2);

    gl_FragColor = mix(_texture1, _texture2, dispPower);
  }
  `;

class DistortionSlider {

  constructor(el, {images, texture, deep, speed, fragment}) {

    // bind this
    this.bindAll(['render', 'nextSlide', 'timer']);

    this.vertex = vertex;

    this.fragment = fragment ? fragment : fragmentDefault;

    this.el = el;
    this.inner = this.el.querySelector('.js-slider__inner');
    this.bullets = [...this.el.querySelectorAll('.js-slider-bullet')];

    this.renderer = null;
    this.scene = null;
    this.clock = null;
    this.camera = null;

    /**
     * Array of images to apply the effect
     * @type {string[]}
     */
    this.images = images;

    /**
     * distortion texture
     * @type {string}
     */
    this.texture = texture;

    this.counter = {
      current: 0,
      prev: this.images.length - 1,
      next: 1,
      total: this.images.length - 1,
    };

    this.state = {
      animating: false,
      initial: true,
    };

    /**
     * @type {{
     *  deep: number, エフェクトのかかり具合
     *  speed: number 切り替えの速度 sec
     *  }}
     */
    this.effect = {
      deep: deep ? deep : .5,
      speed: speed ? speed : 2.5,
    };

    this.bg = null;

    this.init();
  }

  /**
   * event bind
   * @param nameArr {Array}
   */
  bindAll(nameArr) {
    nameArr.forEach(func => this[func] = this[func].bind(this));
  }

  /**
   * init style
   */
  setStyles() {

    this.bullets.forEach((bullet, index) => {
      if (index === 0) return;

      const text = bullet.querySelector('.js-slider-bullet__text');
      const line = bullet.querySelector('.js-slider-bullet__line');

      TweenMax.set(text, {
        alpha: 0.25,
      });
      TweenMax.set(line, {
        scaleX: 0,
        transformOrigin: 'left',
      });
    });

  }

  /**
   * setting camera
   */
  cameraSetup() {

    // 平行投影で遠近感がないカメラ
    this.camera = new THREE.OrthographicCamera(
      this.el.offsetWidth / -2,
      this.el.offsetWidth / 2,
      this.el.offsetHeight / 2,
      this.el.offsetHeight / -2,
      1,
      1000,
    );

    this.camera.lookAt(this.scene.position);
    this.camera.position.z = 1;

  }

  /**
   * scene
   * renderer
   * append canvas
   */
  setup() {

    this.scene = new THREE.Scene();

    // tracking time - performance.now()
    // https://threejs.org/docs/#api/en/core/Clock
    this.clock = new THREE.Clock(true);

    // init renderer
    this.renderer = new THREE.WebGLRenderer({alpha: true});
    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(this.el.offsetWidth, this.el.offsetHeight);

    this.inner.appendChild(this.renderer.domElement);

  }

  /**
   * set texture and images
   */
  loadTextures() {

    // loading a texture uses the ImageLoader
    // Texture object - https://threejs.org/docs/#api/en/textures/Texture
    const loader = new THREE.TextureLoader();
    loader.crossOrigin = '';

    // background images
    this.bg = [];
    this.images.forEach(image => {

      const img = loader.load(`${image}?v=${Date.now()}`, this.render);
      // リピートしないように
      img.wrapS = THREE.ClampToEdgeWrapping;
      img.wrapT = THREE.ClampToEdgeWrapping;
      // いい感じに縮小 (ノイズ少ない)
      img.minFilter = THREE.LinearFilter;
      this.bg.push(img);

    });

    // texture for distortion
    this.disp = loader.load(this.texture, this.render);
    // いい感じに拡大
    this.disp.magFilter = this.disp.minFilter = THREE.LinearFilter;
    // リピートさせる
    this.disp.wrapS = this.disp.wrapT = THREE.RepeatWrapping;
  }

  /**
   * create Mesh
   */
  createMesh() {

    // create material
    this.material = new THREE.ShaderMaterial({
      uniforms: {
        dispPower: {type: 'f', value: 0.0},
        intensity: {type: 'f', value: this.effect.deep},
        texture1: {type: 't', value: this.bg[0]},
        texture2: {type: 't', value: this.bg[1]},
        disp: {type: 't', value: this.disp},
      },
      transparent: true,
      vertexShader: this.vertex,
      fragmentShader: this.fragment,
    });

    // create geometry
    const geometry = new THREE.PlaneBufferGeometry(
      this.el.offsetWidth,
      this.el.offsetHeight,
      1,
    );

    // create mesh
    const mesh = new THREE.Mesh(geometry, this.material);

    this.scene.add(mesh);
  }

  transitionPrev() {
  }

  /**
   * インクリメント時のアニメーション
   */
  transitionNext() {

    TweenMax.to(this.material.uniforms.dispPower, this.effect.speed, {
      value: 1,
      ease: Expo.easeInOut,
      onUpdate: this.render,
      onComplete: () => {
        // init
        this.material.uniforms.dispPower.value = 0.0;
        this.changeTexture();
        this.state.animating = false;
      },
    });

    this.updateControler('next');
  }

  /**
   * コントローラーのアップデート
   * @param direction {string} next or prev
   */
  updateControler(direction) {
    const tl = new TimelineMax({paused: true});

    const current = this.bullets[this.counter.current];
    const next = (direction === 'next') ? this.bullets[this.counter.next] : this.bullets[this.counter.prev];

    const currentText = current.querySelectorAll('.js-slider-bullet__text');
    const nextText = next.querySelectorAll('.js-slider-bullet__text');

    const currentLine = current.querySelectorAll('.js-slider-bullet__line');
    const nextLine = next.querySelectorAll('.js-slider-bullet__line');

    tl
      .to(currentText, 1, {
        alpha: .25,
        ease: Linear.easeNone,
      }, 0)
      .set(currentLine, {
        transformOrigin: 'right',
      }, 0)
      .to(currentLine, 1, {
        scaleX: 0,
        ease: Expo.easeInOut,
      }, 0);

    tl
      .to(nextText, 1, {
        alpha: 1,
        ease: Linear.easeNone,
      }, 1)
      .set(nextLine, {
        transformOrigin: 'left',
      }, 1)
      .to(nextLine, 1, {
        scaleX: 1,
        ease: Expo.easeInOut,
      }, 1);

    tl.play();
  }

  prevSlide() {
    if (this.state.animating) return;

    this.state.animating = true;

    // start animation
    this.transitionPrev();

    // カウンターを進める
    this.counter.current = this.counter.current === this.counter.total ? 0 : this.counter.current - 1;
    this.counter.prev = this.counter.current === this.counter.total ? 0 : this.counter.current - 1;
  }

  nextSlide() {
    if (this.state.animating) return;

    this.state.animating = true;

    // start animation
    this.transitionNext();

    // カウンターを進める
    this.counter.current = this.counter.current === this.counter.total ? 0 : this.counter.current + 1;
    this.counter.next = this.counter.current === this.counter.total ? 0 : this.counter.current + 1;
  }

  /**
   * update texture
   */
  changeTexture() {
    this.material.uniforms.texture1.value = this.bg[this.counter.current];
    this.material.uniforms.texture2.value = this.bg[this.counter.next];
  }

  /**
   * set wheel event
   */
  listeners() {
    window.addEventListener('wheel', this.nextSlide, {passive: true});
  }

  /**
   * autoplay timer
   */
  timer() {
    setInterval(this.nextSlide, 3000);
  }

  /**
   * update render
   * called tweenMax update
   */
  render() {
    this.renderer.render(this.scene, this.camera);
  }

  /**
   * init
   */
  init() {
    this.setup();
    this.cameraSetup();
    this.loadTextures();
    this.createMesh();
    this.setStyles();
    this.render();
    this.listeners();
    this.timer();
  }
}

export default DistortionSlider;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
new DistortionSlider(this.$refs.slider, {
  images: [
    'https://images.unsplash.com/photo-1548112129-b5cf67e9558d',
    'https://images.unsplash.com/photo-1548106755-5c6bf746ca84',
    'https://images.unsplash.com/photo-1547962041-6d2d7c4bdf6e',
  ],
  texture: '/images/texture/01.png',
  deep: 10.0,
});
1
2
3
4
5
6
7
8
9

# BD-2

Blues drive.

const fragment = `
varying vec2 vUv;

// images
uniform sampler2D texture1;
uniform sampler2D texture2;
uniform sampler2D disp;

uniform float dispPower; // 0 ~ 1
uniform float intensity;

void main() {
  vec2 uv = vUv;

  vec4 disp = texture2D(disp, uv);
  vec2 dispVec = vec2(disp.x, disp.y);

  vec2 distPos1 = vec2(uv.x + (dispVec.y * intensity * dispPower), uv.y - (dispVec.y * intensity * dispPower) * .25);
  vec2 distPos2 = vec2(uv.x + (dispVec.x * -(intensity * (1.0 - dispPower))), uv.y - (dispVec.y * -(intensity * (1.0 - dispPower))) * .5);

  vec4 _texture1 = texture2D(texture1, distPos1);
  vec4 _texture2 = texture2D(texture2, distPos2);

  gl_FragColor = mix(_texture1, _texture2, dispPower);
}
`;
new DistortionSlider(this.$refs.slider, {
  images: [
    'https://images.unsplash.com/photo-1494256997604-768d1f608cac',
    'https://images.unsplash.com/photo-1516125073169-9e3ecdee83e7',
    'https://images.unsplash.com/photo-1467011582549-93cad47c167e',
  ],
  texture: '/images/texture/01.png',
  deep: .25,
  fragment,
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Last Updated: 9/24/2019, 12:13:57 PM