Created
August 1, 2020 17:23
-
-
Save photonstorm/e8e15e9a334b3468456e4882cb190638 to your computer and use it in GitHub Desktop.
Phaser 3 Image File Loader class
This file contains hidden or 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
class ImageFileLoader extends Phaser.Events.EventEmitter | |
{ | |
constructor (scene, allowMultipleFiles = true) | |
{ | |
super(); | |
this.scene = scene; | |
this.textures = scene.sys.textures; | |
this.textureKeys = []; | |
this._saveToTextureManager = false; | |
let element = document.createElement('input'); | |
element.type = 'file'; | |
element.accept = 'image/*'; | |
if (allowMultipleFiles) | |
{ | |
element.multiple = 'multiple'; | |
} | |
element.addEventListener('change', (event, inputElement) => this.onChange(event, element), false); | |
this.inputElement = element; | |
} | |
open (...keys) | |
{ | |
this._saveToTextureManager = true; | |
this.textureKeys = keys; | |
this.inputElement.click(); | |
} | |
openAsImage (...keys) | |
{ | |
this._saveToTextureManager = false; | |
this.textureKeys = keys; | |
this.inputElement.click(); | |
} | |
onChange (event, inputElement) | |
{ | |
let fileList = Array.from(inputElement.files); | |
const count = this.textureKeys.length; | |
if (fileList.length === 0) | |
{ | |
return; | |
} | |
else if (count !== 0 && fileList.length > count) | |
{ | |
fileList = fileList.splice(0, count); | |
} | |
fileList.forEach((file) => { | |
if (file.type.startsWith('image/')) | |
{ | |
let filename = file.name.substring(0, file.name.lastIndexOf('.')); | |
let name = filename; | |
if (this.textureKeys.length) | |
{ | |
name = this.textureKeys.shift(); | |
} | |
let img = document.createElement('img'); | |
let reader = new FileReader(); | |
reader.onload = (event) => { | |
img.onload = () => { | |
let texture = (this._saveToTextureManager) ? this.textures.addImage(name, img) : img; | |
this.emit('fileload', name, texture, filename); | |
}; | |
img.src = event.target.result; | |
}; | |
reader.readAsDataURL(file); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment