如下图所示,我有一个用'Chart JS'创建的图表。该图表包含具有各种曲线的线性线。我用各种颜色的“背景色”绘制了这些线之间的区域。
我的问题是,当我在这张图表上创建一个随机点时,我只想创建一个基于颜色的if语句。
例如, 有一个点称为A,该变量称为B。 如果A点在黄色区域,则B为1。 如果A点位于浅灰色区域,则B为2。 像这样的东西。
这是图片:
这是示例代码:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script type="text/javascript">
var x_A = new Array(2, 2, 2.5, 2.5, 2);
var y_A = new Array(2.5 , 3 , 3.5, 2.5 , 2.5);
var c_A = [];
for (var i = 0; i < x_A.length; i++) {
var obj = { x: x_A[i], y: y_A[i] };
c_A.push(obj);
}
var x_B = new Array(0, 1.5, 1.5, 0);
var y_B = new Array(0, 2, 0.5, 0);
var c_B = [];
for (var i = 0; i < x_B.length; i++) {
var obj = { x: x_B[i], y: y_B[i] };
c_B.push(obj);
}
var x_C = new Array(1.5, 1.5, 2, 2, 1.5);
var y_C = new Array(0.5, 2, 3, 2.5, 0.5);
var c_C = [];
for (var i = 0; i < x_C.length; i++) {
var obj = { x: x_C[i], y: y_C[i] };
c_C.push(obj);
}
var r_A = 'rgba(220, 20, 60,1)';
var r_B = 'rgba(255, 255, 56,1)';
var r_C = 'rgba(34, 139, 34,1)';
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: 'X',
showLine: true,
fill: true,
pointRadius: 7,
data: [{
x: 1,
y: 0.9
}],
borderWidth: 1,
pointBackgroundColor: "#000000",
lineTension: 0,
},
{
label:'Zone A',
showLine: true,
fill: true,
backgroundColor: r_A,
pointRadius: 0,
data: c_A,
borderWidth: 1,
borderColor: "#000000",
lineTension: 0,
},
{
label: 'Zone B',
showLine: true,
fill: true,
backgroundColor: r_B,
pointRadius: 0,
data: c_B,
borderWidth: 1,
borderColor: "#000000",
lineTension: 0,
},
{
label: 'Zone C',
showLine: true,
fill: true,
backgroundColor: r_C,
pointRadius: 0,
data: c_C,
borderWidth: 1,
borderColor: "#000000",
lineTension: 0,
},
]
},
options: {
title: {
display: false,
},
tooltips: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
gridLines:
{
display: false
},
scaleLabel: {
display: true
}
}],
yAxes: [{
gridLines:
{
display: false
},
scaleLabel: {
display: true,
}
}]
}
}
});
</script>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<html>
<body>
<div class="w3-row">
<div class="w3-col s3"><p></p></div>
<div class="w3-col s6" align="center"><canvas id="myChart" height="220"></canvas></div>
</div>
<div class="w3-row" align="center"><h2>Color Zone where the point X is located: </h2></div>
</body>
</html>
这是CodePen: