Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
Chart.js - make background text responsive

I am using chart.js for visualization.

I am using the library to create the following chart:

function createConfig(legendPosition, colorName) {
  return {
    type: 'line',
    data: {
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      datasets: [{
        label: 'My First Dataset',
        data: [-91, -85, -70, -96, 70, -81, -85, -66, 47, 26, -7, -4],
        backgroundColor: "",
        borderColor: 'rgb(100, 73, 216)',
        borderWidth: 1
      }]
    },

    options: {
      responsive: true,
      legend: {
        position: legendPosition,
      },
      scales: {
        xAxes: [{
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Month'
          }
        }],
        yAxes: [{
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Value'
          }
        }]
      },
    }
  };
}

window.onload = function(e) {
  var ctx = document.getElementById('chart-legend-bottom').getContext('2d');
  var config = createConfig('bottom', 'purple');
  
  let myLineExtend = Chart.controllers.line.prototype.draw;
  Chart.helpers.extend(Chart.controllers.line.prototype, {
    draw: function() {
      myLineExtend.apply(this, arguments);
      this.chart.chart.ctx.textAlign = "center"
      this.chart.chart.ctx.font = "40px Roboto black";
      this.chart.chart.ctx.fillText("www.google.com", 450, 150)
    }
  });
  
  new Chart(ctx, config);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script>

<body>
  <canvas id="chart-legend-bottom" width="600" height="400"></canvas>
</body>

When displaying the above example on mobile the inserted text does not scale with the chart.

enter image description here

Any suggestions how to scale the text with the screen size?

I appreciate your replies!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can make use of the Plugin Core API. It offers different hooks that may be used for executing custom code. In your case, you could use the afterDraw hook to draw text at a position computed from the chart.scales.

Please take a look at your amended code and see how it works.

new Chart('chart-legend-bottom', {
  type: 'line',
  plugins: [{
    afterDraw: chart => {      
      let xAxis = chart.scales['x-axis-0'];
      let yAxis = chart.scales['y-axis-0'];
      let x = (xAxis.left + xAxis.right) / 2;
      let y = yAxis.getPixelForValue(0);
      let ctx = chart.chart.ctx;
      ctx.save();
      ctx.font = '40px Roboto black';
      ctx.textAlign = 'center';
      ctx.fillText('www.google.com', x, y);
      ctx.restore();
    }
  }],
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    datasets: [{
      label: 'My First Dataset',
      data: [-91, -85, -70, -96, 70, -81, -85, -66, 47, 26, -7, -4],
      backgroundColor: "",
      borderColor: 'rgb(100, 73, 216)',
      borderWidth: 1
    }]
  },
  options: {
    responsive: true,
    legend: {
      position: 'bottom'
    },
    scales: {
      xAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Month'
        }
      }],
      yAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Value'
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script>
<canvas id="chart-legend-bottom" width="600" height="400"></canvas>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda