LoginSignup
0
0

More than 1 year has passed since last update.

画像取得WEBAPI PixabayAPIお試し

Posted at

Pixabay公式

アカウント作ってAPIキーを取得する。特に障壁なし。

per_pageで取得画像枚数を設定できる。3枚が最低限

サンプル Codepen

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Pixabay API サンプルデモ</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>

    <form name="search">
      <input name="key" type="text" placeholder="文字を入力してください">
      <input name="btn" type="submit" value="ボタン">
    </form>

    <div id="result"></div>


    <script src="app.js"></script>

  </body>
</html>
Css
form {
  margin: 25px 0;
  text-align: center;
}
form input[type="text"] {
  width: 80%;
  border: none;
  outline: none;
  padding: 5px 0;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #aaa;
}
form input[type="submit"] {
  padding: 5px 10px;
  border: 1px solid #aaa;
  outline: none;
  color: #000;
  background-color: #fff;
}
form input[type="submit"]:hover {
  color: #fff;
  background-color: #aaa;
  cursor: pointer;
}

img:hover {
  opacity: 0.5;
}

#result {
  width: 90%;
  margin: auto;
  padding: 30px;

}
JS
(function() {

'use strict';


//フォームのボタンがクリックされたら、またはエンターキーが押されたら
document.search.btn.addEventListener('click', function(e) {
  e.preventDefault();  //画面更新をキャンセル


  fetch( createURL(document.search.key.value) )
  .then( function( data ) {
    return data.json();  //JSONデータとして取得する
  })
  .then( function( json ) {

    createImage( json );

  })
})



//リクエスト用のURLを生成する
function createURL( value ) {
  var API_KEY = '*******';
  var baseUrl = 'https://pixabay.com/api/?key=' + API_KEY;
  var keyword = '&q=' + encodeURIComponent( value );
  var option = '&orientation=horizontal&per_page=3';
  var URL = baseUrl + keyword + option;

  return URL;
}


//画像のJSONデータを画面に表示する
function createImage( json ) {
  var result = document.getElementById('result');

  result.innerHTML = '';  //検索するごとに画面をリセットする

  //該当する画像があれば
  if( json.totalHits > 0 ) {
    json.hits.forEach( function( value ) {
      var img = document.createElement('img');
      var a = document.createElement('a');

      a.href = value.pageURL;  //ダウンロード用のサイトURL
      a.target = '_blank';
      img.src = value.previewURL;  //プレビュー用の画像URL

      a.appendChild( img );
      result.appendChild( a );
    })
  }
  else {
    alert('該当する写真がありません');
  }
}

})();
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0