Last active
August 12, 2016 16:10
-
-
Save veltman/929490702f3c95e3260acf9696179d20 to your computer and use it in GitHub Desktop.
Looping pseudo-video w/ sound (sprite)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
div { | |
width: 480px;, | |
height: 250px; | |
margin: 125px auto; | |
} | |
</style> | |
<body> | |
<div><canvas width="480" height="250"></canvas></div> | |
<script> | |
var context = document.querySelector("canvas").getContext("2d"), | |
audioContext = new (window.AudioContext || window.webkitAudioContext)(); | |
var request = new XMLHttpRequest(), | |
image = new Image(); | |
request.responseType = "arraybuffer"; | |
request.open("GET", "llcoolj.wav", true); | |
// XHR complete | |
request.onload = function() { | |
audioContext.decodeAudioData(request.response, success, function(err){ throw err; }); | |
}; | |
image.onload = function() { | |
request.send(); | |
} | |
image.src = "sprite.png"; | |
function success(buffer) { | |
var source = audioContext.createBufferSource(); | |
var gainNode = audioContext.createGain(); | |
// Keep it quiet | |
gainNode.gain.value = 0.2; | |
source.connect(gainNode); | |
gainNode.connect(audioContext.destination); | |
// Set the buffer | |
source.buffer = buffer; | |
source.loop = true; | |
var secondsPerFrame = buffer.duration / 94, | |
t0 = audioContext.currentTime; | |
source.start(0); | |
requestAnimationFrame(update); | |
function update(){ | |
var frame = Math.floor(((audioContext.currentTime - t0) % buffer.duration) / secondsPerFrame); | |
context.drawImage(image, 0, frame * 250, 480, 250, 0, 0, 480, 250); | |
requestAnimationFrame(update); | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment