Skip to content

Instantly share code, notes, and snippets.

@ikeryou
Created April 13, 2017 11:43
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ikeryou/e4820e4ae1d59a354658cb489be02ea2 to your computer and use it in GitHub Desktop.
スマホでの動画インライン再生 for WebGL
# 画面いっぱいに動画をWebGLでインライン再生させる
class InlineMovie
constructor: ->
# video要素
@_video
# テクスチャ
@_tex
# テクスチャ表示するMesh
@_mesh
# -----------------------------------------------
# 初期化
# -----------------------------------------------
init: =>
# このvideo要素から毎フレームキャプチャ
@_video = document.createElement('video')
@_video.preload = 'none'
@_video.autoplay = false
@_video.loop = true
# video要素からテクスチャ生成するやつ
@_tex = new THREE.VideoTexture(@_video)
@_tex.format = THREE.RGBFormat
# テクスチャサイズ可変する場合、ここ設定しておかないと警告でる
@_tex.minFilter = THREE.LinearFilter
@_tex.magFilter = THREE.LinearFilter
# テクスチャ表示するためのMesh
@_mesh = new THREE.Mesh(
new THREE.PlaneBufferGeometry(1,1),
new THREE.MeshBasicMaterial({
map:@_tex
})
)
# ----
# @mainSceneはダミー
# 各自用意したTHREE.Sceneに追加
@mainScene.add(@_mesh)
# ----
# イベント 動画再生準備OK
# 動画のサイズがわかったらMeshのサイズを合わせる
@_video.addEventListener('loadeddata', (e) =>
@_resize()
)
# src指定
@_video.src = '/assets/hoge.mp4'
# 動画の読み込み開始
# PCの場合は普通に再生できるのでここを@_video.play()とかにする
@_video.load()
# -----------------------------------------------
# 毎フレーム実行
# -----------------------------------------------
_update: =>
if @_video.duration? && @_video.duration > 0
# currentTime進める速度は映像ごとに調整
# @_video.play()した場合やらない
@_video.currentTime += 0.02
if @_video.currentTime >= @_video.duration
@_video.currentTime = 0
# 忘れずにやる
# これやらないとテクスチャが更新されない
@_tex.needsUpdate = true
# -----------------------------------------------
# 画面リサイズ時に実行
# -----------------------------------------------
_resize: =>
# 画面サイズ
w = window.innerWidth
h = window.innerHeight
# 画面にFIXするようにMeshのサイズ(scale)を変更
movW = w
movH = @_video.videoHeight * (movW / @_video.videoWidth)
if movH < h
movH = h
movW = @_video.videoWidth * (movH / @_video.videoHeight)
@_mesh.scale.set(movW, movH, 1)
# ---
# このあたりはダミー
# ピクセル等倍にする
@camera.aspect = w / h
@camera.updateProjectionMatrix()
@camera.position.z = h / Math.tan(@camera.fov * Math.PI / 360) / 2
@renderer.setPixelRatio(window.devicePixelRatio || 1)
@renderer.setSize(w, h, true)
@renderer.clear()
# ---
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment