gomesite/js/background.js

83 lines
2.4 KiB
JavaScript

const PREFIX = 'https://gome.page/bg/';
const choose = options => {
const weight_sum = options.reduce((a, b) => a + b.weight, 0);
let choice = Math.floor(Math.random() * weight_sum);
for (const option of options) {
if (choice < option.weight) {
return option;
} else {
choice -= option.weight;
}
}
}
const images = [
{ name: 'lake_cabin', weight: 2 },
{ name: 'paintress_well', weight: 4 },
{ name: 'butterfly_garden', weight: 4 },
{ name: 'duck_island_cottage', weight: 3 },
{ name: 'moon_gate', weight: 2 },
{ name: 'forest_road', weight: 3 },
{ name: 'hiking_trail', weight: 4 },
{ name: 'finnish_hut_far', weight: 2 },
{ name: 'finnish_hut_close', weight: 2 },
{ name: 'mossy_rock', weight: 4 },
{ name: 'sf_japanese_garden', weight: 2 },
{ name: 'wine_hut', weight: 2 },
{ name: 'steiner_granary', weight: 3 },
{ name: 'forest_pond', weight: 3 },
{ name: 'mossy_stumps', weight: 2 },
{ name: 'ritsurin_garden', weight: 2 },
{ name: 'wendelin_chapel', weight: 3 },
{ name: 'buffalo_grass', weight: 1 },
{ name: 'alpine_dairy', weight: 2 },
{ name: 'mist_woods', weight: 4 },
{ name: 'aulne_abbey', weight: 4 },
{ name: 'wood_anemones', weight: 4 },
{ name: 'kyoto_gate', weight: 2 },
];
const image_choice = choose(images);
const html = document.querySelector('html');
const body = document.querySelector('body');
const img = document.createElement('img');
img.id = 'background';
img.src = `${PREFIX}${image_choice.name}.jpg`;
img.srcset = `
${PREFIX}${image_choice.name}-384.jpg 384w,
${PREFIX}${image_choice.name}-512.jpg 512w,
${PREFIX}${image_choice.name}-1024.jpg 1024w,
${PREFIX}${image_choice.name}-2048.jpg 2048w
`;
body.appendChild(img);
const lic = fetch(`https://gome.page/bg/${image_choice.name}.lic`)
.then(response => response.text())
.then(lic => {
let credit = null;
if (lic.startsWith('<')) {
credit = document.createElement('div');
credit.className = 'image-credit';
credit.innerHTML = '<h3>Image credit</h3>' + lic;
} else {
credit = document.createElement('a');
credit.textContent = 'Image credit';
credit.className = 'image-credit';
credit.target = '_blank';
credit.href = lic;
}
if (credit) {
document.querySelector('header').appendChild(credit);
document.querySelector('main').appendChild(credit.cloneNode(true));
}
});
img.addEventListener('load', () => {
html.classList.add('loaded');
});