Generating Random Photo for AI

share link

by bharathrokkadakatti22 dot icon Updated: Nov 28, 2023

technology logo
technology logo

Guide Kit Guide Kit  

Generating a random photo using JavaScript involves a combination of retrieving images from a source and displaying them on a web page. One way to achieve this is by utilizing an API that provides random images. For this example, I'll use the Unsplash API, but you can choose any other API that suits your needs.


Here's a simple example of how you can generate a random photo using JavaScript:


```HTML

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Random Photo Generator</title>

  <style>

    #photo-container {

      text-align: center;

      margin-top: 20px;

    }


    #random-photo {

      max-width: 100%;

      height: auto;

    }

  </style>

</head>

<body>

  <h1>Random Photo Generator</h1>

  <div id="photo-container">

    <img id="random-photo" src="" alt="Random Photo">

  </div>

  <button onclick="getRandomPhoto()">Generate Random Photo</button>


  <script>

    function getRandomPhoto() {

      // Replace 'YOUR_ACCESS_KEY' with your Unsplash API access key

      const accessKey = 'YOUR_ACCESS_KEY';

      const apiUrl = `https://api.unsplash.com/photos/random?client_id=${accessKey}`;


      fetch(apiUrl)

        .then(response => response.json())

        .then(data => {

          const randomPhotoUrl = data.urls.regular;

          document.getElementById('random-photo').src = randomPhotoUrl;

        })

        .catch(error => console.error('Error fetching random photo:', error));

    }


    // Initial load

    getRandomPhoto();

  </script>

</body>

</html>

```

See similar Kits and Libraries