Chart.js Customizing Tick Labels for Mixed Font Styles

。_饼干妹妹 提交于 2021-01-28 07:01:00

问题


I am building a chart with React and Chart.js, and I need to display tick labels that have mixed font styles. Chart.js returns the tick values as a string of the the text passed in as well as the HTML tags that wrap the values we want to italicize.

I tried writing a callback function to return jsx which nulled out the y axis tick marks. Additionally, I have tried applying conditions to the fontStyle prop, and customizing the html in the labels.

let italicizedFont = 'Font'.italics()
console.log(italicizedFont)
var myChart = new Chart(ctx, {
  type: 'horizontalBar',
  data: {
    labels: ["Normal Font", "Mixed <i>Font</i>", `Mixed ${italicizedFont}`, 'Mixed font in <i>Return</i>'],
    datasets: [{
      data: [12, 19, 8],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
      ],
      borderWidth: 1
    }]
  },
  options: {
    responsive: false,
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      yAxes: [{
        ticks: {
          callback: (value, i, values) => {
            if(i !== 3 ){
              return value
            }
            return values[3].replace(/<i>/g, '').replace(/<\/i>/g, '')
        },
          // fontStyle:  'italic'
        }
      }]
    }
  }
});

Code Pen Example

I would expect that Chart.js would convert the string "normal text italicized text" to a string. However, Chart.js seems capable of only returning a fully italicized string "normal text italicized text" or a string with the html tags included.

来源:https://stackoverflow.com/questions/57731460/chart-js-customizing-tick-labels-for-mixed-font-styles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!