Перемещение по временной шкале видео и нажмите

1

Я новичок в GSAP, и я пытаюсь включить перетаскивание и нажимать на пользовательскую графику видео html5 с помощью GSAP. Я прочитал пару сообщений на форуме GSAP, но есть кое-что, что я, очевидно, не могу понять...

Я воспроизвел упрощенный пример в следующем jsfiddle: https://jsfiddle.net/epigeyre/oLmk6b0d/2/

Поэтому я создаю свой перетаскиваемый элемент из элемента, хранящегося в переменной, привязывая его к контейнеру (который является контейнером временной шкалы), а затем добавляет мою функцию onDrag (я думаю, что щелчок будет таким же). Прогресс временной шкалы показан div внутри контейнера временной шкалы, который масштабируется по оси X от 0 до 1. Я думаю, что привязка к текущему времени видео в порядке, но анимация не является (я не понимаю, почему применяется перевод...).

Вот этот конкретный фрагмент:

Draggable.create( timelineProgress, {
  type:'x',
  bounds: timeline, // My timeline container
  onDrag: function() {
    video.currentTime = this.x / this.maxX * video.duration;
    TweenLite.set( timelineProgress, { scaleX: this.x / this.maxX } ) ;
  },
  onClick: function() {
    video.currentTime = this.x / this.maxX * video.duration;
    TweenLite.set( timelineProgress, { scaleX: this.x / this.maxX } ) ;
  }
});

Не могли бы вы помочь мне понять, что происходит? Большое спасибо за вашу помощь!

Теги:
gsap
draggable

1 ответ

1
Лучший ответ

Хорошо, вот здесь решение для тех, кто нуждается в создании пользовательского видеоплеера. Используя GSAP, у вас есть действительно интересное свойство trigger в плагине Draggable.

Вот как я сделал это для видеостраницы HTML5.

var video = document.getElementsByTagName('video')[0],
    play = document.getElementsByClassName('video__play')[0],
    timeline = document.getElementsByClassName('timeline')[0],
    timelineProgress = document.getElementsByClassName('timeline__progress')[0],
    drag = document.getElementsByClassName('timeline__drag')[0];

// Toggle Play / Pause
play.addEventListener('click', togglePlay, false);

function togglePlay() {
  if (video.paused) {
    video.play();
  } else {
    video.pause();
  }
}

// on interaction with video controls
video.onplay = function() {
  TweenMax.ticker.addEventListener('tick', vidUpdate);
};
video.onpause = function() {
	TweenMax.ticker.removeEventListener('tick', vidUpdate);
};
video.onended = function() {
	TweenMax.ticker.removeEventListener('tick', vidUpdate);
};

// Sync the timeline with the video duration
function vidUpdate() {
  TweenMax.set(timelineProgress, {
    scaleX: (video.currentTime / video.duration).toFixed(5)
  });
  TweenMax.set(drag, {
    x: (video.currentTime / video.duration * timeline.offsetWidth).toFixed(4)
  });
}

// Make the timeline draggable
Draggable.create(drag, {
  type: 'x',
  trigger: timeline,
  bounds: timeline,
  onPress: function(e) {
    video.currentTime = this.x / this.maxX * video.duration;
    TweenMax.set(this.target, {
      x: this.pointerX - timeline.getBoundingClientRect().left
    });
    this.update();
    var progress = this.x / timeline.offsetWidth;
    TweenMax.set(timelineProgress, {
      scaleX: progress
    });
  },
  onDrag: function() {
    video.currentTime = this.x / this.maxX * video.duration;
    var progress = this.x / timeline.offsetWidth;
    TweenMax.set(timelineProgress, {
      scaleX: progress
    });
  },
  onRelease: function(e) {
    e.preventDefault();
  }
});
video {
  display: block;
  width: 100%;
  height: auto;
}

.timeline {
  width: 100%;
  height: 10px;
  background-color: black;
  cursor: pointer;
  position: relative;
}

/* Here is the dragger that I will use to move the video 
* current time forward or backward.
* I have added a background color for you to see it
* but just remove it in production.
*/

.timeline__drag {
  width: 1px;
  height: 20px;
  top: -10px;
  background-color: yellow;
  position: absolute;
  z-index: 2;
  transform-origin: 0 0;
}

.timeline__progress {
  display: block;
  width: 100%;
  height: 100%;
  background-color: green;
  transform: scaleX(0);
  transform-origin: 0 0;
  position: relative;
  z-index: 1;
}

button {
  margin-top: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.0/utils/Draggable.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.0/TweenMax.min.js"></script>

<video>
  <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4">
</video>
<div class="timeline">
  <div class="timeline__drag"></div>
  <span class="timeline__progress"></span>
</div>
<button class="video__play">Play / Pause video</button>

Я должен поблагодарить Карла за форум GSAP за его замечательную помощь!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню