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="bubble" data-chart-data-value="{"labels":["January","February","March","April"],"datasets":[{"label":"Dataset 1","backgroundColor":"#93c5fd","data":[{"x":20,"y":32,"r":15},{"x":30,"y":30,"r":25},{"x":35,"y":20,"r":13},{"x":40,"y":10,"r":10}]}]}"></canvas></div>
1
2
3
4
5
6
7
8
9
10
11
12
<% @chart_data = { labels: [ "January", "February", "March", "April" ], datasets: [{ label: "Dataset 1", backgroundColor: "#93c5fd", data: [{ x: 20, y: 32, r: 15 }, { x: 30, y: 30, r: 25 }, { x: 35, y: 20, r: 13 }, { x: 40, y: 10, r: 10 }] }]} %><div class="relative i-full" style="block-size: 400px;"> <%= tag.canvas aria: { label: "Example" }, role: "img", data: { controller: "chart", chart_type_value: "bubble", 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
import { Controller } from "@hotwired/stimulus"import { Chart, registerables } from "https://esm.sh/chart.js@4.5.0?standalone"export default class extends Controller { static values = { type: { type: String, default: "line" }, data: Object, options: Object } initialize() { Chart.register(...registerables) Chart.defaults.backgroundColor = getComputedStyle(document.body).backgroundColor Chart.defaults.borderColor = getComputedStyle(document.body).borderColor Chart.defaults.color = getComputedStyle(document.body).color Chart.defaults.font.family = getComputedStyle(document.body).fontFamily Chart.defaults.font.size = 12 } 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 } }}