凡例をクリックすると、以下の画像に示すように、データ シリーズによって関連付けられた値のセットが非表示になるため、chart.js スパイダー チャートの凡例のクリックを無効にしたいと思います。
私の要件は、データセットを無効にしたくないということです。チャートのクリックで preventDefault(); を試しましたが、機能しません。
コードサンプルを下記に添付します。ご確認ください。
<!doctype html>
<html>
<head>
<title>Radar Chart</title>
<script src="../dist/Chart.bundle.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div style="width:75%">
<canvas id="canvas"></canvas>
</div>
<script>
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var randomColorFactor = function() {
return Math.round(Math.random() * 255);
};
var randomColor = function(opacity) {
return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';
};
var config = {
type: 'radar',
data: {
labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"],
datasets: [{
label: "My First dataset",
backgroundColor: "rgba(0,0,0,0.5)",
pointBackgroundColor: "rgba(220,220,220,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
}, {
label: "My Second dataset",
backgroundColor: "rgba(0,120,0,0.5)",
pointBackgroundColor: "rgba(151,187,205,1)",
hoverPointBackgroundColor: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
},]
},
options: {
legend: {
position: 'top',
onClick: (e) => e.stopPropagation()
},
title: {
display: true,
text: ''
},
scale: {
reverse: false,
gridLines: {
color: ['black']
},
ticks: {
beginAtZero: true
}
}
}
};
window.onload = function() {
window.myRadar = new Chart(document.getElementById("canvas"), config);
};
</script>
</body>
</html>
ベストアンサー1
ドキュメントによると、onClick
イベント オブジェクトを公開する凡例のハンドラーがあります。stopPropagation
これを使用すると、データ シリーズの非表示が停止します。
let chart = new Chart(elem.find('canvas')[0], {
type: 'line',
data: {
labels: [],
datasets: []
},
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
onClick: (e) => e.stopPropagation()
}
}
});
上記は ES6 です。サポートされているブラウザを使用していない場合は、以下が古い ES5 に相当します。
legend: {
onClick: function (e) {
e.stopPropagation();
}
}
Chartjs はその後に独自のクリック イベントを登録する必要があるlegend.onClick
ため、実行が停止します。