根据Twitch上的游戏流更改站点的背景

时间:2017-06-21 11:12:46

标签: javascript background twitch

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";
      }
  });
});

通过Twitch API,您可以获得流式游戏的名称,如何获得带有游戏图像的URL?我有可以使用的数据库吗?

1 个答案:

答案 0 :(得分: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字段来确定你想要的那个(它可能会添加一些类似命名的游戏,所以你需要选择正确的一个)。

一旦确定哪个游戏对象是正确的游戏对象,请使用相关的框属性来获取GameBox图像网址,例如games[0].box.large