Is it possible to resize an image coming from an API call? I am extracting an image from an API and trying to insert into a div on the page. The API is "NASA image of the day" and its a new image from nasa each day. Sometimes the image is vertical, and sometimes the image is horizontal depending on the day. What is the best way to handle this situation? I don't want the image to exceed the div it is inside of (40rem x 40rem), and right now the image posts really big on the screen and isn't contained inside of the div at all.
HTML:
<section id="section--1">
<div >
<div >
<h2 >Image of the day <button>view</button></h2>
<h3 >
View the "image of the day" taken by NASA satellites in space
</h3>
</div>
</div>
<div ></div>
<!-- <figure >
<img src="/img/space.jpg" alt=""/>
</figure> -->
CSS:
.parent__el {
height: 40rem;
width: 40rem;
margin: 0 auto;
}
JavaScript:
const imageContainer = document.querySelector('.parent__el')
const loadImage = async function() {
try {
// 1) loading recipe
const res = await fetch('https://api.nasa.gov/planetary/apod?api_key=BSw3P3LRHk0brFlI5xMlVkaTdwUZuA3arh0A5ziV');
const data = await res.json();
if(!res.ok) throw new Error(`${data.message} (${res.status})`);
console.log(data)
// 2) rendering recipe
const markup = `
<div >
<img src="${data.url}" alt="" />
</div>
`;
imageContainer.innerHTML = markup;
} catch(err) {
alert(err)
}
}
loadImage()
CodePudding user response:
You could also try setting the image as the background image of your space_photo
container:
const markup = `
<div style="background-image: url('${data.url}'); background-size:cover;">
</div>
`;
You would then have to give the class "space__photo" an appropriate size though (height and width 100% for example, so it stretches the entire length of your parent_el)
CodePudding user response:
give your image an id, "img". in your div rendering part, do this:
let img = document.getElementById("img")
if(img.style.height >= img.style.width) {
img.style.height = '40px'
} else {
img.style.width = '40px'
}
This makes it so when the image is verticle, it renders it as 40px height. When it is horizontal, it is 40px width.