guest_worker/scanimation/interfaces/animation/script.js
2020-01-08 18:04:33 +01:00

79 lines
1.8 KiB
JavaScript

let cnv = document.getElementById('cnv'),
ctx = cnv.getContext('2d')
let frames_folder = '../frames/',
imgs = [],
new_imgs = []
let add_img = (new_img) => {
let img = new Image()
img.src = `${frames_folder}${new_img}`
img.onload = function(){
console.log(`loaded ${new_img}`)
}
imgs.push(img)
}
// SOCKET //////////////////////////////////////////////////////////////////////
let socket = io.connect('/')
socket.on('connection', function(){
console.log('connected to node server')
socket.emit('animationInit')
makeAnimation()
})
socket.on('frameData', function(data){
imgs.length < data.frames.length ? new_imgs = data.frames.slice(imgs.length) : new_imgs = []
new_imgs.forEach(function(img){ add_img(img) })
})
// ANIMATION ///////////////////////////////////////////////////////////////////
let frames_per_sec = 7,
current_frame = 0,
forward = true
function makeAnimation(){
let now,
delta = 0,
last = timeStamp(),
step = 1/frames_per_sec
function frame() {
now = timeStamp()
delta += Math.min(1, (now - last) / 1000)
while(delta > step){
delta -= step
update(step)
}
last = now
requestAnimationFrame(frame)
}
requestAnimationFrame(frame)
}
function update(step){
if (imgs.length < 1) return;
if (current_frame == (imgs.length-1)) forward = false
else if (current_frame == 0) forward = true
forward ? current_frame++ : current_frame--
ctx.drawImage(imgs[current_frame], 0, 0)
// console.log(current_frame)
}
function timeStamp(){ return window.performance && window.performance.now ? window.performance.now() : new Date().getTime() }