Created
August 15, 2023 09:06
-
-
Save image72/c9fbe592e93c1ab314580110f4952297 to your computer and use it in GitHub Desktop.
wrap chartjs to web component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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