Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

116
Vistas
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.

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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)
}
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.