Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion projeto-completo/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
<span class="loading-overlay" id="loadOverlay">
loading...
</span>
<img id="carregarImg" />
<figure id="figure">
<img id="carregarImg" />
</figure>
</div>
<div class="alinhador">
<button onclick="attachImage()">Get a color image</button>
Expand Down
42 changes: 42 additions & 0 deletions projeto-completo/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ function refImg() {
return imgElement;
}

function refFigure() {
const figure = document.getElementById('figure');
console.log('Figure', figure);
return figure;
}

const getImageURL = async (type = ''/* normal or gray image*/) => {
const opts = {
method: 'GET',
Expand All @@ -23,6 +29,40 @@ const getImageURL = async (type = ''/* normal or gray image*/) => {
return urlObj.url;
}

const getImageId = (url) => {
const urlSplited = url.split('/id/');
const imageId = urlSplited[1].split('/')[0];
return imageId;
}

const getImageInfo = async (url) => {
const imageId = getImageId(url);
const opts = {
method: 'GET',
headers:{
'Content-Type': 'application/json'
},
};
let imageInfo = null;
try {
imageInfo = await fetch(`https://picsum.photos/id/${imageId}/info`, opts).then((response) => response.json());
} catch (error) {
alert('erro ao buscar dados da imagem');
enableButtons();
}
return imageInfo;
}

const addImageCaption = (imageInfo) => {
const figure = refFigure();
const oldFigCaption = figure.getElementsByTagName('figcaption')[0];
const figCaption = document.createElement("figcaption");
const text = document.createTextNode("Autor: " + imageInfo.author);
figCaption.appendChild(text);
oldFigCaption != undefined && figure.removeChild(oldFigCaption);
figure.appendChild(figCaption);
}

const disableButtons = () => {
const buttons = document.querySelectorAll('button');
buttons.forEach(button => button.disabled = true);
Expand All @@ -43,8 +83,10 @@ async function attachImage(type = ''){
setLoadingOverlay('inherit');
const imgTagRef = refImg();
const imageUrl = await getImageURL(type);
const imageInfo = await getImageInfo(imageUrl);
imgTagRef.onload = ()=> setLoadingOverlay('none');
imgTagRef.src = imageUrl;
addImageCaption(imageInfo);

enableButtons();
}