树状图chart.js文本换行



在下面的代码中,我可以绘制树映射,并在每个树单元中显示标记。但是如果是长单词,文本就会溢出磁贴

我需要确保这个词留在瓷砖里,即使它的意思是放。。。。在某些字符之后。我该如何实现这些目标?在提供解决方案之前,请先看看我使用的chart.js和Treemap的版本。非常感谢:(


var topTags = [
{tag:'android',num:42657},{tag:'reactjs',num:38844},{tag:'php',num:34381},{tag:'sql',num:29996},
];
var canvas = document.getElementById("treemap");
var ctx = canvas.getContext("2d");
var chart = window.chart = new Chart(ctx, {
type: "treemap",
data: {
datasets: [{
tree: topTags,
key: "num",
groups: ['tag'],
spacing: 0.5,
borderWidth: 1.5,
fontColor: "black",
borderColor: "grey"
}]
},
options: {
maintainAspectRatio: false,
legend: { display: false },
tooltips: { enabled: false }
}
});

图表。JS和树图版本:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-chart-treemap@0.2.3"></script>

我通过将文本拆分为多行来解决这个问题,只要超过最大宽度,就开始一行。

const chart = new Chart(context, {
type: 'treemap',
data:  {
datasets: [
{
/* ... */
labels: {
display: true,
formatter(ctx: TreemapScriptableContext) {
if (ctx.type !== 'data') {
return;
}
return splitLabelToFit(ctx.raw["_data"].label, ctx.raw.w*0.9, ctx);
}
}
}
],
},
});
function splitLabelToFit(label: string, maxWidth: number, ctx: TreemapScriptableContext) {
const words = label.split(' ');
const lines = [];
let currentLine = '';
for (let i = 0; i < words.length; i++) {
const word = words[i];
const newLine = currentLine + ' ' + word;
const width = ctx.chart.ctx.measureText(newLine).width;
if (width < maxWidth) {
currentLine = newLine;
} else {
lines.push(currentLine);
currentLine = word;
}
}
lines.push(currentLine);
return lines;
}

最新更新