2017-06-21 23 views
0

的JavaScript:更改基於遊戲流上抽搐的部位背景

$(document).ready(function game_background() { 
    var name, key_t; 
    name = "TWITCH_USERNAME"; 
    key_t = "TWITCH_API_KEY"; 

    $.getJSON("https://api.twitch.tv/kraken/streams/" + name + '?client_id=' + key_t, function (data) { 
     /*If they are online shows the game's image*/ 
     if (data.stream) { 
      document.body.style.backgroundImage = 'url(URL_IMAGE_GAME)'; 
     } 
     /*If they are offline shows a red background*/ 
     else { 
      document.body.style.background = "red"; 
     } 
    }); 
}); 

通過抽搐API,你可以得到的流遊戲的名字,我怎麼能得到一個URL與遊戲圖片?有我可以使用的數據庫嗎?

回答

0

使用/kraken/search/games?q=star&type=suggest其中star是您的遊戲名稱進行搜索。

從DOC例如,將返回:

{ 
    "_links": { 
    "self": "https://api.twitch.tv/kraken/search/games?q=star&type=suggest", 
    }, 
    "games": [ 
    { 
     "box": { 
     "large": "http://static-cdn.jtvnw.net/ttv-boxart/StarCraft%20II:%20Wings%20of%20Liberty-272x380.jpg", 
     "medium": "http://static-cdn.jtvnw.net/ttv-boxart/StarCraft%20II:%20Wings%20of%20Liberty-136x190.jpg", 
     "small": "http://static-cdn.jtvnw.net/ttv-boxart/StarCraft%20II:%20Wings%20of%20Liberty-52x72.jpg", 
     "template": "http://static-cdn.jtvnw.net/ttv-boxart/StarCraft%20II:%20Wings%20of%20Liberty-{width}x{height}.jpg" 
     }, 
     "logo": { 
     "large": "http://static-cdn.jtvnw.net/ttv-logoart/StarCraft%20II:%20Wings%20of%20Liberty-240x144.jpg", 
     "medium": "http://static-cdn.jtvnw.net/ttv-logoart/StarCraft%20II:%20Wings%20of%20Liberty-120x72.jpg", 
     "small": "http://static-cdn.jtvnw.net/ttv-logoart/StarCraft%20II:%20Wings%20of%20Liberty-60x36.jpg", 
     "template": "http://static-cdn.jtvnw.net/ttv-logoart/StarCraft%20II:%20Wings%20of%20Liberty-{width}x{height}.jpg" 
     }, 
     "popularity": 114, 
     "name": "StarCraft II: Wings of Liberty", 
     "_id": 63011880, 
     "_links": { }, 
     "giantbomb_id": 20674   
    }, 
    ... 
    ] 
} 

然後,您可以解析JSON並使用每個項目的name領域games,以確定這是你想要的(它可能增加一些類似命名的遊戲,所以你需要選擇正確的)。

一旦你確定哪個遊戲對象是正確的,使用相關的box屬性來獲取GameBox圖像url,例如, games[0].box.large

+0

此外,我不相信有任何GameBoxes提供更高的分辨率。 '/ kraken/games/top'返回相同的一組圖像尺寸。 – JBC