我想在网页上显示随机的 Wikimedia Commons 图像。
像这样的东西:http: //lkozma.net/blog/random-wiki-image-wallpaper/除了作为网页。
你会怎么做呢?
谢谢
我想在网页上显示随机的 Wikimedia Commons 图像。
像这样的东西:http: //lkozma.net/blog/random-wiki-image-wallpaper/除了作为网页。
你会怎么做呢?
谢谢
找到你
<!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>
我觉得这会得到一些反对意见,但无论如何我都会展示伪代码。
设置
抓取 Wikimedia Commons,以便获得一堆图像 URL。将它们放入数据库中。为每个 URL 指定一个顺序 ID。
用法
当您的网页加载时,请使用服务器端代码随机提取其中一个 URL - 从 1 到 COUNT(*) 的随机 ID。该代码还可以检查该 URL 是否仍然存在于 Wikimedia Commons 上。如果 URL 已被删除(或更改?),则生成另一个 ID 并从数据库中提取该 URL。(每周或每两周重新抓取 Wikimedia Commons 应该使您的 URL 表保持最新。)