Add chart.min.js into my Project

exma2's picture
Forums: 

Hello,

im working on a project to insert specific charts into my h5p Coure-Presentation. 

I thought i can easy use some canvas element to show my graph. 

I want to use the chart.min.js, downloaded from https://www.jsdelivr.com/package/npm/chart.js. 

If im trying to import the class with "import Chart from 'chart.min.js';" i cant add some element from that class.  I also used other methods to integrate this file like this:

var h5pScript = document.createElement('script');
  h5pScript.setAttribute('charset', 'UTF-8');
  h5pScript.setAttribute('src', 'https://cdn.jsdelivr.net/npm/chart.js@3.2.0/dist/chart.min.js');
  document.body.appendChild(h5pScript);

 

or this in library.json:

 "preloadedJs": [
    {
      "path": "chart.min.js"
    },

but it never works. 

Is there someone who can help me? 

My Code, who im trying to integrate the class:

 // Inheritance
  C.prototype = Object.create(H5P.EventDispatcher.prototype);
  C.prototype.constructor = C;

  /**
   * Attach function called by H5P framework to insert H5P content into
   * page
   *
   * @param {jQuery} $container
   */
  C.prototype.attach = function ($container) {
    var self = this;

    var canvas = document.createElement('canvas');
    canvas.id = "chartLayer"; //irrelevant
    canvas.height = 350;
    canvas.width = 550;
    canvas.style.position = "absolute";
    canvas.style.border = "1px solid";

    var ctx = document.getElementById('chartLayer').getContext('2d');

    var myChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(255, 159, 64, 0.2)'
          ],
          borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(255, 159, 64, 1)'
          ],
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });

    $container.append(canvas);

  }
serettig's picture

Hi,

If you want to use the cutting edge "import ..." statement from ES, you must transpile your code to something browsers understand (ES5 or maybe ES6 nowaways).

I think a script tag needs the URL of the script in the url attribute not a full link. That's why it doesn't work in the second case.

If you add files to the preloadedJs part of library.json, you must also copy in the file into the same directory and you must make sure to add your own custom code after the import of the library.

Sebastian

exma2's picture

  document.body.appendChild(div_graph);
      var script = document.createElement('script');
      script.type = "text/javascript";
      script.addEventListener("load", function(event) {
        console.log("script loaded :)");
        var myChart = echarts.init(document.getElementById('graphid'));
        var option;
        // ab hier einfach ersetzen mit Arten von charts *1
        option = {
          title:
            {
              text: self.options.titelChart,
              left: "top",
              top: "left",
              textStyle: {
                fontSize: 10
              },

            },
          tooltip: {
            // Mouse over zusatz über die daten (kleiens Feld)
            trigger: 'axis'
          },
          legend: {
            data: ['Spannung', 'Strom' ]
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            // zeigt die Werte auf x und y an
            containLabel: true
          },
          toolbox: {
            feature: {
              // Damit ein Download gemacht werden kann (kleiner Button oben rechts)
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            // Daten auf der xAchse sind zwischen den Strichen
            boundaryGap: true,
            data: ['0', '10', '20', '30', '40', '50', '60']
          },
          yAxis: {
            type: 'value',
            data: ['0', '100', '200', '300', '400', '500', '600']
          },
          series: [
            {
              name: 'Spannung',
              type: 'line',
              // Stack verhindert hier, dass die Graphen übereinander laufen
              stack: '总量',
              data: [100, 150, 200, 250, 300, 350, 400]
            },
            {
              name: 'Strom',
              type: 'line',
              stack: '总量',
              // Die Line wird nicht eckig gezeichnet
              smooth: false,
              data: [50, 100, 150, 200, 250, 300, 350]
            }
          ]
        };
        //bis hier *1
        option && myChart.setOption(option);
      });
      script.src = "https://cdnjs.cloudflare.com/ajax/libs/echarts/4.2.1/echarts-en.min.js";
      document.getElementsByTagName('head')[0].appendChild(script);

      $container.append(div_graph);
serettig's picture

Great that it works now. One thing to note: It's relatively unusual in H5P to lazy load JavaScript. If it's possible, it would probably be better to add the js file to the library and reference it in library.json. Then the bundler that's included in the H5P core can include it when it generates bundles (called caches).