104 lines
2.5 KiB
JavaScript
104 lines
2.5 KiB
JavaScript
/* global XMLHttpRequest, Image */
|
|
|
|
let imgCache = {}
|
|
|
|
function powerOfTwo (n) {
|
|
return n && (n & (n - 1)) === 0
|
|
}
|
|
|
|
function GET (url, istext) {
|
|
return new Promise((resolve, reject) => {
|
|
var xmlHttp = new XMLHttpRequest()
|
|
|
|
xmlHttp.onreadystatechange = function () {
|
|
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
|
|
resolve(xmlHttp.responseText)
|
|
} else if (xmlHttp.readyState === 4 && xmlHttp.status >= 400) {
|
|
let err = new Error(xmlHttp.status)
|
|
err.request = xmlHttp
|
|
reject(err)
|
|
}
|
|
}
|
|
|
|
xmlHttp.open('GET', url, true)
|
|
istext && (xmlHttp.responseType = 'text')
|
|
xmlHttp.send(null)
|
|
})
|
|
}
|
|
|
|
function smartGET (data) {
|
|
if (typeof data === 'string') {
|
|
data = {
|
|
url: data,
|
|
type: 'text'
|
|
}
|
|
}
|
|
|
|
if (!data.type) data.type = 'text'
|
|
let istext = (data.type !== 'image' && data.type !== 'file')
|
|
|
|
let url = data.url
|
|
if (!url) throw new Error('URL is required!')
|
|
|
|
if (data.type === 'json') {
|
|
return new Promise((resolve, reject) => {
|
|
GET(url).then((dtext) => {
|
|
try {
|
|
let jsonp = JSON.parse(dtext)
|
|
return resolve(jsonp)
|
|
} catch (e) {
|
|
reject(e)
|
|
}
|
|
}, reject)
|
|
})
|
|
}
|
|
|
|
return GET(data.url, istext)
|
|
}
|
|
|
|
function loadImage (url, onlyReturn = false, nowarn = false) {
|
|
if (onlyReturn && imgCache[url]) {
|
|
return imgCache[url]
|
|
}
|
|
|
|
// Ensure we don't load a texture multiple times
|
|
if (imgCache[url]) return new Promise((resolve, reject) => resolve(imgCache[url]))
|
|
|
|
return new Promise((resolve, reject) => {
|
|
let img = new Image()
|
|
|
|
img.onload = function () {
|
|
// Friendly warnings
|
|
if ((!powerOfTwo(img.width) || !powerOfTwo(img.height)) && !nowarn) {
|
|
console.warn(`warn: image ${url} does not have dimensions that are powers of two. 16x16 to 128x128 recommended.`)
|
|
}
|
|
|
|
if ((img.width / img.height) !== 1 && !nowarn) {
|
|
console.warn(`warn: image ${url} does not have an aspect ratio of 1 to 1.`)
|
|
}
|
|
|
|
imgCache[url] = img
|
|
resolve(img)
|
|
}
|
|
|
|
img.onerror = function (e) {
|
|
reject(e)
|
|
}
|
|
|
|
img.src = url
|
|
})
|
|
}
|
|
|
|
function imageToSampler (img) {
|
|
let canvas = document.createElement('canvas')
|
|
let ctx = canvas.getContext('2d')
|
|
canvas.width = img.width
|
|
canvas.height = img.height
|
|
ctx.drawImage(img, 0, 0, img.width, img.height)
|
|
return function (x, y) {
|
|
return ctx.getImageData(x, y, 1, 1).data
|
|
}
|
|
}
|
|
|
|
export default { GET: smartGET, imageToSampler, loadImage }
|