var Player = document.querySelector('#ambient-player') var FirstCanvas = document.getElementById("ambient-canvas-1") var SecondCanvas = document.getElementById("ambient-canvas-2") var FirstCtx = FirstCanvas.getContext("2d") var SecondCtx = SecondCanvas.getContext("2d") const FrameInterval = 1600 const CanvasOpacity = "0.4" let IntervalId let FirstFrame = true const Draw = () => { if (FirstFrame) { FirstCtx.drawImage(Player, 0, 0, FirstCanvas.width, FirstCanvas.height) ToFirstCanvas() } else { SecondCtx.drawImage(Player, 0, 0, SecondCanvas.width, SecondCanvas.height) ToSecondCanvas() } FirstFrame = !FirstFrame } const ToFirstCanvas = () => { FirstCanvas.style.opacity = CanvasOpacity SecondCanvas.style.opacity = "0" } const ToSecondCanvas = () => { SecondCanvas.style.opacity = CanvasOpacity FirstCanvas.style.opacity = "0" } const StartDrawing = () => {IntervalId = window.setInterval(Draw, FrameInterval)} const PauseDrawing = () => {if (IntervalId) window.clearInterval(IntervalId)} const init = () => { Player.pause() Player.play() Player.addEventListener("play", StartDrawing, false) Player.addEventListener("pause", PauseDrawing, false) Player.addEventListener("ended", PauseDrawing, false) FirstCanvas.style.transition = SecondCanvas.style.transition = `opacity ${FrameInterval}ms` } const cleanup = () => { Player.removeEventListener("play", StartDrawing) Player.removeEventListener("pause", PauseDrawing) Player.removeEventListener("ended", PauseDrawing) PauseDrawing() } window.addEventListener("load", init) window.addEventListener("unload", cleanup)