chartjs / Chart.js

Simple HTML5 Charts using the <canvas> tag
https://www.chartjs.org/
MIT License
64.42k stars 11.89k forks source link

Change Plugin Text Style (Font Size) on Chart Canvas Area in ChartJS #6850

Closed JajaRodriguez closed 4 years ago

JajaRodriguez commented 4 years ago

`
var plugin = { id: 'plugin', beforeDraw: function(chart) {

    var width = chart.chart.width,
      height = chart.chart.height,
      ctx = chart.chart.ctx,
      xScale = chart.scales['x-axis-0'],
      yScale = chart.scales['y-axis-0'];

    ctx.restore();
    ctx.font = "1em sans-serif";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    // ctx.fillText("s(A)", width * .28, height * .70);
    ctx.fillText(
      "s(A)",
      xScale.getPixelForValue('2005'),
      yScale.getPixelForValue(3)
    );
    ctx.fillText(
      "s(B)",
      xScale.getPixelForValue('2015'),
      yScale.getPixelForValue(9)
    );
    ctx.save();
  }
};

var xCoord = new Array(1997, 2003, 2005, 2009, 2014, 2018, 2019);
var yCoord = new Array(1, 3, 5, 3, 6, 10, 9);
var c = [];
for (var i = 0; i < xCoord.length; i++) {
  var obj = {
    x: xCoord[i],
    y: yCoord[i]
  };
  c.push(obj);
}
var ctx = document.getElementById('myTau').getContext('2d');
var myTau = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'None',
      data: c,
      borderWidth: 1,
      borderColor: "#ef1414",
      fill: false,
      cubicInterpolationMode: 'monotone'
    }]
  },
  plugins: [plugin],
  options: {
    title: {
      display: true,
      text: 'My Chart 2'
    },
    tooltips: {
      mode: 'nearest',
      intersect: true
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        scaleLabel: {
          display: true,
          labelString: 'Year Assembly',
          fontSize: 14
        }
      }],
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Aquifer Values Corresponding',
          fontSize: 15
        }
      }]
    }
  }
});

<canvas id="myTau" height="120"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>`

Here is github.io online javascript viewer link: Click

There is a chartjs canvas area and I've created the plugin text in chart area. I want to change the plugin font size, moreover if possible, I want to change responsively. If it can not be possible, how can I change the font size of "s(A) & s(B)" plugin font size? I've tried ctx.fontsized but it cannot be resolved.

kurkle commented 4 years ago

https://codepen.io/kurkle/pen/oNgZgXJ?editors=1010