ブログの背景を京都のいまの天気によって切り替えてみたくなって OpenWeather という天気 API を使って素朴に background-image を切り替えるようにした。アカウント作ったら API が使えて便利、ちょろっと js 書いて完成した。いま京都は曇りです。
openweathermap.org
写真は過去に取ってたやつを使っている、冬が好きなので夏だけど問答無用で雪の様子が出ます。
const url = 'https://api.openweathermap.org/data/2.5/weather?lat=35&lon=135.7&units=Metric&appid=xxx';
fetch(url).then(res => res.json()).then(json => {
const weather = json.weather;
if (!weather || !weather[0]) { return; }
const mainWeather = weather[0].main;
const backgroundImageSrcs = {
Clear: 'https://cdn-ak.f.st-hatena.com/images/fotolife/h/hogashi/20210715/20210715000656_original.jpg',
Clouds: 'https://cdn-ak.f.st-hatena.com/images/fotolife/h/hogashi/20210714/20210714235934_original.jpg',
Rain: 'https://cdn-ak.f.st-hatena.com/images/fotolife/h/hogashi/20210714/20210714233101_original.jpg',
Snow: 'https://cdn-ak.f.st-hatena.com/images/fotolife/h/hogashi/20210714/20210714233101_original.jpg',
};
const imageSrc = backgroundImageSrcs[mainWeather];
document.querySelector('html').style.backgroundImage = `url('${imageSrc}')`;
});
html {
background: top / contain repeat-y url('');
}
body {
background-color: rgba(255, 255, 255, 0.4);
}
天気の API 探したらこの記事を見つけたので見つつやってて、確かにアカウントつくった直後は API 使えなかったけどちょっと待ったら使えるようになるみたいな感じだった。
dev.classmethod.jp