Chart.js legend took up too much spaces(Chart.js 图例占用太多空间)
问题描述
我在使用 chart.js 图例时遇到了一些问题.长文本的图例占用了太多空间,导致我的饼图尺寸减小:
I was having some problem with chart.js legend. The legend with long text took up too much spaces which resulting in the reduce in the size of my pie chart:
另一个例子是这样的:
如果我得到更多的图例,圆环图最终会变得越来越小.
If I got more legend, the doughnut chart will eventually becomes smaller and smaller.
我尝试设置 maxWidth 但无济于事.
I tried to set maxWidth but to no avail.
var options = {
layout: {
padding: {
top: 5
}
},
responsive: true,
maintainAspectRatio: false,
legend: {
display: true,
position: 'right',
maxWidth: 100,
onClick: null
},
animation: {
animateScale: true,
animateRotate: true
},
};
有什么想法吗?
我尝试按照这个 [解决方案][3] 创建一个 html 图例:
I tried to follow this [solution][3] to create a html legend:
<div class="box-body" style="height:350px;">
<div class="float-left">
<div class="float-left" style="width:70%">
<canvas id="brandChart" style="position: relative; height: 350px;"></canvas>
</div>
<div class="float-left" style="width:30%">
<div id="js-legend" class="chart-legend">
</div>
</div>
</div>
它确实限制了图例的宽度,但这导致了另一个问题,即在我折叠并展开 div 之后,画布丢失了,我只剩下图例 div.
It did restricted the width for legend, but then this lead to another problem which is after I collapsed and expanded the div, the canvas just went missing and I am only left with the legend div.
推荐答案
首先,使用它的原生属性设置画布的宽度和高度(做not 使用 style
属性),像这样:
First off, set canvas's width and height using it's native attributes (do not use style
attribute), like so :
<canvas id="brandChart" width="700" height="350"></canvas>
注意:宽度应该是高度的两倍
note: width should be twice the height
然后,在图表选项中将 responsive
属性设置为 false
,如下所示:
Then, set responsive
property to false
in your chart options, as such :
options: {
responsive: false,
...
}
ᴅᴇᴍᴏ
var chart = new Chart(brandChart, {
type: 'doughnut',
data: {
labels: ['Etronin Home Appliances Service & trading Pte Ltd', 'Giant'],
datasets: [{
data: [30, 70],
backgroundColor: ['#2196f3', '#4caf50']
}]
},
options: {
responsive: false,
legend: {
display: true,
position: 'right',
onClick: null
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="brandChart" width="700" height="350"></canvas>
这篇关于Chart.js 图例占用太多空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Chart.js 图例占用太多空间
基础教程推荐
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01