x
1
<canvas style="max-block-size: 400px" aria-label="Example" role="img" data-controller="chart" data-chart-type-value="line" data-chart-data-value="{"labels":["January","February","March","April","May","June","July"],"datasets":[{"label":"Dataset 1","borderColor":"#93c5fd","backgroundColor":"#93c5fd","data":[65,59,80,81,56,55,40]},{"label":"Dataset 2","borderColor":"#fda4af","backgroundColor":"#fda4af","data":[35,69,20,91,36,25,20]}]}"></canvas>
1
2
3
4
5
6
7
8
9
<% @chart_data = {
labels: [ "January", "February", "March", "April", "May", "June", "July" ],
datasets: [
{ label: "Dataset 1", borderColor: "#93c5fd", backgroundColor: "#93c5fd", data: [65, 59, 80, 81, 56, 55, 40] },
{ label: "Dataset 2", borderColor: "#fda4af", backgroundColor: "#fda4af", data: [35, 69, 20, 91, 36, 25, 20] }
]
} %>
<%= tag.canvas style: "max-block-size: 400px", aria: { label: "Example" }, role: "img", data: { controller: "chart", chart_type_value: "line", chart_data_value: @chart_data.to_json } %>
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
import { Controller } from "@hotwired/stimulus"
import { Chart, registerables } from "https://cdn.skypack.dev/chart.js@4.4.6?min"
Chart.register(...registerables)
Chart.defaults.backgroundColor = getCssVariableValue("--color-primary")
Chart.defaults.borderColor = getCssVariableValue("--color-border")
Chart.defaults.color = getCssVariableValue("--color-text")
Chart.defaults.font.family = getCssVariableValue("--font-system-ui")
Chart.defaults.font.size = 12
function getCssVariableValue(variableName) {
return getComputedStyle(document.documentElement).getPropertyValue(variableName).trim()
}
export default class extends Controller {
static values = { type: { type: String, default: "line" }, data: Object, options: Object }
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 }
}
}