taiko-web/public/src/js/canvasasset.js

94 lines
2.0 KiB
JavaScript
Raw Normal View History

2018-09-14 00:55:23 +02:00
class CanvasAsset{
2018-09-20 01:20:26 +02:00
constructor(view, layer, position){
2018-09-14 00:55:23 +02:00
this.ctx = view.ctx
this.controller = view.controller
this.position = position
this.animationFrames = {}
this.speed = 1000 / 60
this.animationStart = 0
2018-09-20 01:20:26 +02:00
this.layer = layer
2018-09-14 00:55:23 +02:00
}
draw(){
if(this.animation){
2018-09-20 01:20:26 +02:00
var u = (a, b) => typeof a === "undefined" ? b : a
var frame = 0
2018-10-03 11:48:18 +02:00
var ms = this.controller.getElapsedTime()
2018-09-14 00:55:23 +02:00
if(this.animationEnd){
if(ms > this.animationEnd.ms){
this.animationEnd.callback()
delete this.animationEnd
return this.draw()
}
}
var index = Math.floor((ms - this.animationStart) / this.speed)
if(Array.isArray(this.animation)){
frame = this.animation[this.mod(this.animation.length, index)]
2018-09-14 00:55:23 +02:00
}else{
frame = this.mod(this.animation, index)
2018-09-14 00:55:23 +02:00
}
2018-09-20 01:20:26 +02:00
var pos = this.position(frame)
if(this.image){
this.ctx.drawImage(this.image,
u(pos.sx, pos.x), u(pos.sy, pos.y),
u(pos.sw, pos.w), u(pos.sh, pos.h),
pos.x, pos.y, pos.w, pos.h
)
}
if(pos.callback){
pos.callback()
}
2018-09-14 00:55:23 +02:00
}
}
mod(length, index){
return ((index % length) + length) % length
2018-09-14 00:55:23 +02:00
}
addFrames(name, frames, image){
var framesObj = {
frames: frames
}
if(image){
framesObj.image = assets.image[image]
}
this.animationFrames[name] = framesObj
}
setAnimation(name){
var framesObj = this.animationFrames[name]
this.animationName = name
2018-09-20 01:20:26 +02:00
if(framesObj){
this.animation = framesObj.frames
if(framesObj.image){
this.image = framesObj.image
}
}else{
this.animation = false
2018-09-14 00:55:23 +02:00
}
}
getAnimation(){
return this.animationName
}
2018-09-20 01:20:26 +02:00
getAnimationLength(name){
var frames = this.animationFrames[name].frames
2018-09-14 00:55:23 +02:00
if(Array.isArray(frames)){
return frames.length
}else{
return frames
}
}
setUpdateSpeed(speed){
this.speed = speed
}
setAnimationStart(ms){
this.animationStart = ms
}
setAnimationEnd(ms, callback){
if(typeof ms === "undefined"){
2018-09-14 00:55:23 +02:00
delete this.animationEnd
}else{
this.animationEnd = {
ms: ms,
callback: callback
}
}
}
}