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

344
Visualizações
Cannot create Chart using Chart.JS @ 2.9.4

I am trying to create a chart using Chart.JS (v2.9.4) but am unable to. Here is the relevant HTML

      <canvas
        id="groupPerformanceChart"
        class="lineClass"
        width="340"
        height="220"
        style="margin-top: 2px; height: 220px; width: 340px;"
      ></canvas>

and here is the relevant JS

  var ctx = $("#groupPerformanceChart");
  if (!ctx) {
    console.log("Context not available");
    return
  }
  else {
    console.log("Context available", ctx)
  }
  let myChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: currLabels,
      datasets: dataSet,
    },
    options: {
      responsive: true,
      scales: {
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
              max: 10,
            },
          },
        ],
      },
    },
  });

and here is what it says in the console:

Context available 
jQuery.fn.init {context: document, selector: '#groupPerformanceChart'}

Failed to create chart: can't acquire context from the given item

Interestingly, the chart shows up sometimes if I trigger HMR in dev environment but obviously this won't work for production. I also have other charts in other places that are created the same way and work fine so this one has me stumped.

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

0

The problem is most likely that you have the chart inside a template, which causes it not to be rendered in the moment that you are running the jQuery selector and constructing the chart.

jQuery will always return a value even if no objects have been found. So your check will always say that a context has been found. To fix this, you have to check the length of the jQuery result:

var ctx = $("#groupPerformanceChart");
if (ctx.length <= 0) {
  console.log("Context not available");
  return;
}
else {
  console.log("Context available", ctx)
}
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