x
1
2
3
<div class="relative i-full" style="block-size: 400px;"> <canvas aria-label="Example" role="img" data-controller="chart" data-chart-type-value="doughnut" data-chart-data-value="{"labels":["Chrome","Safari","Firefox","Edge","Other"],"datasets":[{"label":"Visitors","backgroundColor":["#8ec5ff","#193cb8","#1447e6","#2b7fff","#51a2ff"],"data":[275,200,187,173,90]}]}"></canvas></div>1
2
3
4
5
6
7
8
<% @chart_data = { labels: [ "Chrome", "Safari", "Firefox", "Edge", "Other" ], datasets: [{ label: "Visitors", backgroundColor: ["#8ec5ff", "#193cb8", "#1447e6", "#2b7fff", "#51a2ff"], data: [275, 200, 187, 173, 90] }]} %><div class="relative i-full" style="block-size: 400px;"> <%= tag.canvas aria: { label: "Example" }, role: "img", data: { controller: "chart", chart_type_value: "doughnut", chart_data_value: @chart_data.to_json } %></div>
CSS is not required or multiple files are needed, check the notes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { Controller } from "@hotwired/stimulus"import { Chart, registerables } from "https://esm.sh/chart.js@4.5.1?standalone"export default class extends Controller { static values = { type: { type: String, default: "line" }, data: Object, options: Object } initialize() { const style = getComputedStyle(document.body) Chart.register(...registerables) Chart.defaults.color = style.color Chart.defaults.datasets.line.tension = 0.35 Chart.defaults.datasets.radar.tension = 0 Chart.defaults.elements.arc.borderRadius = 6 Chart.defaults.elements.bar.borderRadius = 6 Chart.defaults.elements.point.radius = 0 Chart.defaults.font.family = style.fontFamily Chart.defaults.font.size = 12 Chart.defaults.interaction.intersect = false Chart.defaults.plugins.legend.display = false Chart.defaults.plugins.legend.labels.usePointStyle = true Chart.defaults.plugins.legend.position = "bottom" Chart.defaults.plugins.tooltip.backgroundColor = style.backgroundColor Chart.defaults.plugins.tooltip.bodyColor = style.color Chart.defaults.plugins.tooltip.borderColor = style.borderColor Chart.defaults.plugins.tooltip.borderWidth = 1 Chart.defaults.plugins.tooltip.boxPadding = 4 Chart.defaults.plugins.tooltip.caretSize = 0 Chart.defaults.plugins.tooltip.titleColor = style.color Chart.defaults.plugins.tooltip.usePointStyle = true Chart.defaults.scale.grid.color = style.borderColor } connect() { this.chart = new Chart(this.element, this.#settings) } disconnect() { this.chart.destroy() } get #settings() { return { type: this.typeValue, data: this.dataValue, options: this.optionsValue } }}