Here is my custom-element code for my chart with chart.js npm.
import Chart from 'chart.js';
class ChartElement extends HTMLElement {
constructor() {
super();
this._shadow = this.attachShadow({ mode: 'open' });
this._root = document.createElement('canvas');
this._root.setAttribute("id", "myChart");
this._root.setAttribute("style", "width: 100%");
this._shadow.appendChild(this._root);
this._parent = document.querySelector("chart-elem");
}
connectedCallback() {
this._parent.style.display = "block";
let savedData = sessionStorage.getItem('chartData');
if (savedData && savedData !== 'undefined' && !this._chartData)
this._chartData = savedData;
this._connected = true;
if (this._chartData) {
this.render();
}
}
render() {
const ctx = this._shadow.getElementById('myChart').getContext('2d');
let delayed;
//Gradient Fill
let gradient = ctx.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'rgba(58,123,213,1)')
gradient.addColorStop(1, 'rgba(0,210,255,0.3)')
const labels = [
'2012',
'2013',
'2014',
'2015',
'2016',
'2017',
'2018',
'2019',
'2020'
];
const data = {
labels,
datasets: [{
data: [
211, 326, 165, 350, 420, 370, 500, 375, 415
],
label: "Minecraft Sales",
fill: true,
backgroundColor: gradient,
borderColor: '#fff',
pointBackgroundColor: "#fff",
tension: 0.5,
}]
}
const config = {
type: "line",
data: data,
options: {
radius: 5,
hitRadius: 60,
hoverRadius: 12,
responsive: true,
animation: {
onComplete: () => {
delayed = true;
},
delay: (context) => {
let delay = 0;
if (context.type === "data" && context.mode === "default" && !delayed) {
delay = context.dataIndex * 120 + context.datasetIndex * 100;
}
return delay;
},
},
scales: {
y: {
ticks: {
callback: function (value) {
return '$' + value + 'M';
}
}
}
}
},
};
const myChart = new Chart(ctx, config)
}
}
window.customElements.define('chart-elemnent', ChartElement);
It does not work but I can not understand why it’s not working xd?
I’m testing this in a Premium site also tested with a free site (in preview mode and live). But can not understand why it’s not working? Is there a bug or what?