Skip to content

Instantly share code, notes, and snippets.

@image72
Created August 15, 2023 09:06
Show Gist options
  • Save image72/c9fbe592e93c1ab314580110f4952297 to your computer and use it in GitHub Desktop.
Save image72/c9fbe592e93c1ab314580110f4952297 to your computer and use it in GitHub Desktop.
wrap chartjs to web component
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chart.js Web Component</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<chart-js>
{
"type": "bar",
"data": {
"labels": ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
"datasets": [{
"label": "# of Votes",
"data": [12, 19, 3, 5, 2, 3],
"backgroundColor": ["red", "blue", "yellow", "green", "purple", "orange"]
}]
},
"options": {
"scales": {
"y": {
"beginAtZero": true
}
}
}
}
</chart-js>
<script>
class ChartJsElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
const config = JSON.parse(this.getAttribute('value') || this.innerHTML.trim());
const canvas = document.createElement('canvas');
this.shadowRoot.appendChild(canvas);
new Chart(canvas, config);
}
}
customElements.define('chart-js', ChartJsElement);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment