Skip to content

Instantly share code, notes, and snippets.

@PhilOwen
Created November 17, 2016 03:55
Show Gist options
  • Save PhilOwen/84e43e99ca1e694294934a75c10c488d to your computer and use it in GitHub Desktop.
Save PhilOwen/84e43e99ca1e694294934a75c10c488d to your computer and use it in GitHub Desktop.
ElectronとD3.jsで世界銀行のAPIを呼んでみる

HTMLやJSでデスクトップアプリを作れるElectronを使ってみる。
世界銀行のデータAPIを呼んで、 ベトナムのGDPの変遷をD3.jsでグラフ化してみた。 ついでに、アニメーションで、表示する年代を 1980-2000から1990-2010へぬるっと動かしてみた。

Electronでは、メインのプロセスと描画のプロセスが別れている。 D3は、描画プロセスのほうで処理する。

World Bank APIは、ブラウザからJSでデータを取ろうとすると、 Access-Control-Allow-Originの問題で失敗する。 が、Electronだと大丈夫。
今回はJSONでデータを受け取っているが、XMLなどでも出力できる。 GDP以外にも多数の指標が使えて、わりと面白い。

References

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="d3">
</div>
</body>
<script>
require('./renderer.js')
</script>
</html>
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = require('url')
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({width: 800, height: 600})
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
{
"name": "electron-worldbank-api",
"version": "0.1.0",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"devDependencies": {
"electron": "^1.4.1"
},
"dependencies": {
"d3": "^4.3.0"
}
}
const d3 = require("d3");
const width = 800,
height = 600;
let svg = d3.select("#d3").append("svg")
.attr("width", width)
.attr("height", height);
let xScale80 = d3.scaleLinear()
.domain([1980, 2000])
.range([10, width-10]);
let xScale90 = d3.scaleLinear()
.domain([1990, 2010])
.range([10, width-10]);
let yScale = d3.scaleLinear()
.domain([0, 120000000000])
.range([height-10, 10]);
d3.json('http://api.worldbank.org/countries/vn/indicators/NY.GDP.MKTP.CD?format=json', data => {
let circles = svg.selectAll("circle")
.data(data[1])
.enter()
.append("circle")
.attr("cx", d => xScale80(d.date))
.attr("cy", d => yScale(d.value))
.attr("r", 4)
.attr("fill", "red");
circles
.transition()
.delay(1000)
.duration(2000)
.attr("cx", d => xScale90(d.date));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment