はじめに
どうもSeiyaです!これまで天気・人口アプリを作成してきました。次は金融関連のアプリを作成していきます!
コード
HTML
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>金融ダッシュボード</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
text-align: center;
margin: 20px;
}
.container {
max-width: 800px;
margin: auto;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input, button {
padding: 10px;
margin: 10px;
font-size: 16px;
}
button {
cursor: pointer;
}
canvas {
max-width: 100%;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container">
<h1>📊 金融ダッシュボード</h1>
<h2>💱 為替レート</h2>
<button onclick="fetchExchangeRate()">最新の為替レート取得</button>
<p id="exchange-rate"></p>
<h2>📈 仮想通貨価格</h2>
<button onclick="fetchCryptoPrice()">最新の仮想通貨価格取得</button>
<p id="crypto-price"></p>
<h2>💰 投資シミュレーション</h2>
<label>元本: <input type="number" id="initial-amount" value="100000" min="0"></label>
<label>年利(%): <input type="number" id="interest-rate" value="5" min="0"></label>
<label>年数: <input type="number" id="years" value="10" min="1"></label>
<button onclick="calculateSavings()">シミュレーション</button>
<p id="savings-result"></p>
<canvas id="savingsChart"></canvas>
</div>
<script>
function fetchExchangeRate() {
fetch('https://api.exchangerate-api.com/v4/latest/USD')
.then(response => response.json())
.then(data => {
document.getElementById("exchange-rate").innerText = `1 USD = ${data.rates.JPY} JPY`;
})
.catch(error => console.error("エラー: ", error));
}
function fetchCryptoPrice() {
fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd')
.then(response => response.json())
.then(data => {
document.getElementById("crypto-price").innerText = `Bitcoin価格: $${data.bitcoin.usd}`;
})
.catch(error => console.error("エラー: ", error));
}
function calculateSavings() {
const initialAmount = parseFloat(document.getElementById("initial-amount").value);
const interestRate = parseFloat(document.getElementById("interest-rate").value) / 100;
const years = parseInt(document.getElementById("years").value);
let labels = [];
let data = [];
let amount = initialAmount;
for (let i = 0; i <= years; i++) {
labels.push(`${i}年`);
data.push(amount);
amount *= (1 + interestRate);
}
document.getElementById("savings-result").innerText = `元本: ${initialAmount.toLocaleString()}円 → ${years}年後: ${data[data.length - 1].toLocaleString()}円`;
const ctx = document.getElementById("savingsChart").getContext("2d");
// 既存のチャートを削除する前に、存在を確認
if (window.savingsChart instanceof Chart) {
window.savingsChart.destroy();
}
window.savingsChart = new Chart(ctx, {
type: "line",
data: {
labels: labels,
datasets: [{
label: "貯金成長",
data: data,
borderColor: "green",
borderWidth: 2
}]
}
});
}
</script>
</body>
</html>
解説
HTML構造
HTML
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>金融ダッシュボード</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!DOCTYPE html>
:HTML5を宣言<html lang="ja">
:日本語のページであることを指定<meta charset="UTF-8">
:UTF-8エンコーディングを指定(日本語対応)<meta name="viewport" content="width=device-width, initial-scale=1.0">
:スマホ対応のためのレスポンシブデザイン設定<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
:グラフ描画ライブラリ Chart.js を読み込む
CSS(デザイン設定)
HTML
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
text-align: center;
margin: 20px;
}
.container {
max-width: 800px;
margin: auto;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input, button {
padding: 10px;
margin: 10px;
font-size: 16px;
}
button {
cursor: pointer;
}
canvas {
max-width: 100%;
margin-top: 20px;
}
</style>
全体のデザイン
body
:背景色をグレー (#f0f0f0
) にし、フォントをArial
に設定.container
:白背景、中央配置、影をつけてカード風デザインinput, button
:適度なパディング・フォントサイズを設定し、見やすくcanvas
:グラフが大きすぎないように調整
HTMLのボタンや入力フォーム
HTML
<h2>💱 為替レート</h2>
<button onclick="fetchExchangeRate()">最新の為替レート取得</button>
<p id="exchange-rate"></p>
「為替レート取得」ボタンをクリックすると fetchExchangeRate()
が実行され、データが <p id="exchange-rate"></p>
に表示される。
HTML
<h2>📈 仮想通貨価格</h2>
<button onclick="fetchStockPrice()">最新の仮想通貨価格取得</button>
<p id="crypto-price"></p>
同様に、仮想通貨価格の取得ボタンもある。
HTML
<h2>💰 投資シミュレーション</h2>
<label>元本: <input type="number" id="initial-amount" value="100000" min="0"></label>
<label>年利(%): <input type="number" id="interest-rate" value="5" min="0"></label>
<label>年数: <input type="number" id="years" value="10" min="1"></label>
<button onclick="calculateSavings()">シミュレーション</button>
<p id="savings-result"></p>
<canvas id="savingsChart"></canvas>
投資シミュレーションの設定
元本
(initial-amount
)、年利
(interest-rate
)、年数
(years
) を入力する- ボタンを押すと
calculateSavings()
を実行 - 計算結果は
<p id="savings-result"></p>
に表示 canvas
要素を使い、貯金の成長をグラフ化
JavaScriptの機能
為替レート取得
HTML
function fetchExchangeRate() {
fetch('https://api.exchangerate-api.com/v4/latest/USD')
.then(response => response.json())
.then(data => {
document.getElementById("exchange-rate").innerText = `1 USD = ${data.rates.JPY} JPY`;
})
.catch(error => console.error("エラー: ", error));
}
fetch()
を使い、APIから最新のUSD/JPYレートを取得data.rates.JPY
を取得し、ページ内に表示catch(error => console.error("エラー: ", error))
でエラー処理
仮想通貨価格取得
HTML
function fetchStockPrice() {
fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd')
.then(response => response.json())
.then(data => {
document.getElementById("crypto-price").innerText = `Bitcoin価格: $${data.bitcoin.usd}`;
})
.catch(error => console.error("エラー: ", error));
}
Bitcoinの最新価格を取得し、表示
投資シミュレーション(複利計算+グラフ描画)
HTML
function calculateSavings() {
const initialAmount = parseFloat(document.getElementById("initial-amount").value);
const interestRate = parseFloat(document.getElementById("interest-rate").value) / 100;
const years = parseInt(document.getElementById("years").value);
let labels = [];
let data = [];
let amount = initialAmount;
for (let i = 0; i <= years; i++) {
labels.push(`${i}年`);
data.push(amount);
amount *= (1 + interestRate);
}
document.getElementById("savings-result").innerText = `元本: ${initialAmount.toLocaleString()}円 → ${years}年後: ${data[data.length - 1].toLocaleString()}円`;
const ctx = document.getElementById("savingsChart").getContext("2d");
// 既存のグラフを削除
if (window.savingsChart instanceof Chart) {
window.savingsChart.destroy();
}
// Chart.jsでグラフを作成
window.savingsChart = new Chart(ctx, {
type: "line",
data: {
labels: labels,
datasets: [{
label: "貯金成長",
data: data,
borderColor: "green",
borderWidth: 2
}]
}
});
}
元本 × (1 + 年利)^年数
の計算を行う計算結果をリスト (data[]
) に保存し、Chart.jsで 成長曲線を描画window.savingsChart.destroy();
で 前のグラフを削除してから新しいグラフを描画