现在我在每个饼图中使用onHover
来添加一些缩放,但我想使用mouseenter and mouseleave
。因此,在每个饼图的mouseenter
上,它会添加一些缩放/缩放,在mouseleave
上,我希望它恢复到原始状态。
CCD_ 5或CCD_。
这是代码笔:https://codepen.io/graydirt/pen/NWNZNyQ
谢谢大家!
var ctx = document.getElementById('chartPie').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Green'],
datasets: [{
label: '# of Votes',
data: [12, 19, 20],
backgroundColor: [
'red',
'blue',
'green'
],
datalabels: {
color: '#000'
}
}]
},
options: {
legend: {
display: false
},
layout: {
padding: 5
},
onHover: function (evt, elements) {
let segment;
if (elements && elements.length) {
segment = elements[0];
this.chart.update();
selectedIndex = segment["_index"];
segment._model.outerRadius += 5;
} else {
if (segment) {
segment._model.outerRadius -= 5;
}
segment = null;
}
}
}
});
.chart-pie {
width: 400px;
height: 400px;
margin: auto;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>
<div class="container p-4">
<div class="chart-pie position-relative">
<canvas id="chartPie"></canvas>
</div>
</div>
您的代码已经被设计为在mouseout时返回到原始大小,但您有一个微妙的错误。
您需要在图表外部定义segment
变量。保存对段的引用后,mouseout
事件将触发,onHover
处理程序将饼图返回到其原始大小。
请参阅下面的附加示例:
let segment;
var ctx = document.getElementById('chartPie').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Green'],
datasets: [{
label: '# of Votes',
data: [12, 19, 20],
backgroundColor: [
'red',
'blue',
'green'
],
datalabels: {
color: '#000'
}
}]
},
options: {
legend: {
display: false
},
layout: {
padding: 5
},
onHover: function(evt, elements) {
if (elements && elements.length) {
segment = elements[0];
this.chart.update();
selectedIndex = segment["_index"];
segment._model.outerRadius += 5;
} else {
if (segment) {
segment._model.outerRadius -= 5;
}
segment = null;
}
}
}
});
.chart-pie {
width: 400px;
height: 400px;
margin: auto;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>
<div class="container p-4">
<div class="chart-pie position-relative">
<canvas id="chartPie"></canvas>
</div>
</div>