Project:
Loading screen with Base64 image in Playcanvas (WebGL)
What I try to do:
Change the image when the Website is loaded with other language (index.html?language=xy)
What I already have:
I get the default image in my WebGL loading javascript.
var logo = document.createElement('img');
logo.src = 'here is my base64 code';
splash.appendChild(logo);
logo.onload = function() {
splash.style.display = 'block';
};
I thought it would be the best option to list all languages in an object, and invoke the object with the language that is currently selected.
Why I can't figure it out myself:
As I just started creating javascript projects, I need to lookup many thing, but when I search up my issue I get stuff like this Base64 encode a javascript object
CodePudding user response:
Define all the images in an object
const images = { 'us': 'data:image/jpeg;base64,...', 'nl': 'data:image/jpeg;base64,...', 'fallback': 'data:image/jpeg;base64,...' }
Parse the query paramters, use a fallback if not given
const urlSearchParams = new URLSearchParams(window.location.search); const params = Object.fromEntries(urlSearchParams.entries()); let lanuageKey = params['language']; if (!images[lanuageKey]) { lanuageKey = 'fallback'; }
Add the image with desired base64
var logo = document.createElement('img'); logo.src = images[lanuageKey]; document.body.appendChild(logo);
Putting this all together, will give something like the following snippet:
Note 1: Stack Snippets can't read the query params, so you'll need to try this locally
Note 2: Due to the 30k max chars, I had to remove the base64's
const images = {
'us': 'data:image/jpeg;base64...',
'nl': 'data:image/jpeg;base64...',
'fallback': 'data:image/jpeg;base64...'
}
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
let lanuageKey = params['language'];
if (!images[lanuageKey]) {
lanuageKey = 'fallback';
}
var logo = document.createElement('img');
logo.src = images[lanuageKey];
document.body.appendChild(logo);