Add chart.min.js into my Project
Submitted by exma2 on Thu, 04/29/2021 - 11:01
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
Mon, 05/10/2021 - 21:15
Permalink
Hi,If you want to use the
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
Tue, 05/11/2021 - 22:52
Permalink
Solution - Thanks for help!
serettig
Wed, 05/12/2021 - 19:18
Permalink
Great that it works now. One
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).