随机维基媒体共享图像在网页上

时间:2014-08-01 16:52:12

标签: wikimedia-commons

我想在网页上显示随机的维基共享资源图像。

像这样:http://lkozma.net/blog/random-wiki-image-wallpaper/除了作为网页。

你会怎么做呢?

由于

2 个答案:

答案 0 :(得分:2)

找到你

<!doctype html>
<style>
html { 
  background: no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
</style>

<body>

your stuff here

</body>

<script>
var image_width = 1024;
var interval = 5000;

/*
 * puzzle together the long wikimedia API query URL
 */
var url = 'http://commons.wikimedia.org/w/api.php';
url += '?action=query&generator=random';
url += '&grnnamespace=6';     // only return images (6)
url += '&prop=imageinfo'
url += '&iiprop=url';
url += '&iiurlwidth=' + image_width;
url += '&format=json&callback=processWikimediaJson';

var image = document.createElement('img');
image.onload = function () {
      document.body.parentNode.style.backgroundImage = 'url(' + image.src + ')';
};

/*
 * JSONP callback that traverses the JSON and sticks it into the html background CSS 
 */
function processWikimediaJson(json) {
    var jpg = [];
      for (var id in json.query.pages) {
          jpg.push(json.query.pages[id].imageinfo[0].thumburl);
      }
      image.src = jpg.pop();
}

/*
 * to circumvent crosssite scripting restrictions we need to insert a script tag
 * that gets JSONP from wikimedia API. This JSONP is wrapped in a callback, which
 * we defined above
 */
function getRandomImageJson() {
    var script = document.createElement('script');
    script.src = url;
    document.body.appendChild(script);     
    document.body.removeChild(script);     

    // loop
    window.setTimeout(getRandomImageJson, interval);
}

// initial nudge to the loop
getRandomImageJson();
</script>

答案 1 :(得分:0)

我觉得这会得到一些挫折,但无论如何我都会展示伪代码。

设置

Scrape Wikimedia Commons让你得到一堆图片网址。 把它们放在数据库中。 为每个URL提供一个顺序ID。

<强>用法

当你的网页加载时,让服务器端代码随机抽取其中一个网址 - 随机ID从1到COUNT(*)。 该代码还可以检查该URL是否仍然存在于Wikimedia Commons中。如果URL已被删除(或更改?),则生成另一个ID并从数据库中提取该URL。 (每周或每周重新编辑Wikimedia Commons应该保持你的URL表足够流畅。)

相关问题