Skip to content

Instantly share code, notes, and snippets.

@jshirius
Created March 1, 2021 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jshirius/8aea292374c44a705719e163fba67e16 to your computer and use it in GitHub Desktop.
Save jshirius/8aea292374c44a705719e163fba67e16 to your computer and use it in GitHub Desktop.
javascript-bubbleを使った図の描画、イベントハンドラを取り出すサンプル
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!-- 参考-->
<!-- https://tobiasahlin.com/blog/chartjs-charts-to-get-you-started/#10-bubble-chart -->
<h2>参考サイトのbubble-chartにイベントを追加した例</h2>
<canvas id="bubble-chart" style="min-height: 250px; height: 250px; max-height: 70%; max-width: 70%;"></canvas>
<div id="kakusi" hidden>
<button>なにかクリックしたから、このボタンを表示するよ</button>
</div>
<p>参考サイト</p>
<a href="https://tobiasahlin.com/blog/chartjs-charts-to-get-you-started/#10-bubble-chart">10 Chart.js example charts to get you started</a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<script>
kakusi = document.getElementById("kakusi");
new Chart(document.getElementById("bubble-chart"), {
type: 'bubble', //「scatter」でも良いが、「bubble」だと大きさも表現できるのでbubbleの方が良さげ
data: {
labels: "Africa",
datasets: [
{
label: ["China"],
backgroundColor: "rgba(255,221,50,0.2)",
borderColor: "rgba(255,221,50,1)",
data: [{
x: 21269017,
y: 5.245,
r: 15
},
{
x: 11269017,
y: 5.245,
r: 15
}]
}, {
label: ["Denmark"],
backgroundColor: "rgba(60,186,159,0.2)",
borderColor: "rgba(60,186,159,1)",
data: [{
x: 258702,
y: 7.526,
r: 10
}]
}, {
label: ["Germany"],
backgroundColor: "rgba(0,0,0,0.2)",
borderColor: "#000",
data: [{
x: 3979083,
y: 6.994,
r: 15
}]
}, {
label: ["Japan"],
backgroundColor: "rgba(193,46,12,0.2)",
borderColor: "rgba(193,46,12,1)",
data: [{
x: 4931877,
y: 5.921,
r: 15
}]
}
]
},
options: {
title: {
display: true,
text: 'Predicted world population (millions) in 2050'
}, scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: "Happiness"
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: "GDP (PPP)"
}
}]
},
events: ['click'],
onHover: function(e, el) {
//onClickだけでも良いかも
//if (! el || el.length === 0) return;
//console.log('onHover : label ' + el[0]._model.label);
},
onClick: function (e, el) {
if (! el || el.length === 0) return;
//console.log('onClick : label ' + el[0]._model);
//以下の記述でオブジェクト全体をみることができるよ
console.dir(el);
var s = "_datasetIndex=" + el[0]._datasetIndex + " _lindex=" + el[0]._index + " labels=" + el[0]._chart
alert(s)
//$("#kakusi").css("display", "none");
kakusi.style.display = "block";
}
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment