본문으로 건너뛰기Skip to content
예제 첫화면Examples home

Chart.js 어댑터로 차트 만들기Build a chart with a Chart.js adapter

예제 안의 어댑터가 CDN에서 Chart.js 4를 불러와 chartAdapter로 이어 줘요. 불러오는 동안 온 갱신은 모아 두었다가 로드가 끝나면 그려요.The adapter in this example loads Chart.js 4 from a CDN and connects it as chartAdapter. Updates that arrive while loading are queued and drawn once the script is ready.

심화Advanced
직접 써 보기Live previewChart.js 어댑터로 차트 만들기Build a chart with a Chart.js adapter

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="fromSelection">선택으로 막대 차트</button>
    <button type="button" id="allRows">전체 행</button>
    <button type="button" id="lineChart">꺾은선</button>
    <button type="button" id="clear">지우기</button>
  </div>
  <div id="grid" style="height: 320px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('fromSelection').addEventListener('click', () => actions.fromSelection(api));
document.getElementById('allRows').addEventListener('click', () => actions.allRows(api));
document.getElementById('lineChart').addEventListener('click', () => actions.lineChart(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const rows = [
  { id: 1, region: '서울', q1: 120, q2: 150, q3: 180, q4: 210, note: '본사' },
  { id: 2, region: '부산', q1: 90, q2: 110, q3: 140, q4: 130, note: '항만' },
  { id: 3, region: '대구', q1: 70, q2: 85, q3: 95, q4: 120, note: '내륙' },
  { id: 4, region: '인천', q1: 100, q2: 130, q3: 125, q4: 160, note: '공항' },
  { id: 5, region: '광주', q1: 60, q2: 75, q3: 90, q4: 80, note: '호남' },
  { id: 6, region: '대전', q1: 80, q2: 95, q3: 110, q4: 140, note: '충청' },
  { id: 7, region: '울산', q1: 110, q2: 105, q3: 150, q4: 170, note: '공단' },
  { id: 8, region: '제주', q1: 50, q2: 65, q3: 70, q4: 95, note: '관광' },
];
const columns = [
  { id: 'region', title: '지역', width: 110 },
  { id: 'q1', title: '1분기(백만원)', kind: 'number', editable: true, width: 120 },
  { id: 'q2', title: '2분기(백만원)', kind: 'number', editable: true, width: 120 },
  { id: 'q3', title: '3분기(백만원)', kind: 'number', editable: true, width: 120 },
  { id: 'q4', title: '4분기(백만원)', kind: 'number', editable: true, width: 120 },
  { id: 'note', title: '메모', editable: true, width: 110 },
];
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart() {
  return window.Chart;
}
function loadChartJs(onReady) {
  if (globalChart() !== undefined) {
    onReady();
    return;
  }
  let script = document.querySelector('script[data-chartjs]');
  if (script === null) {
    script = document.createElement('script');
    script.src = CDN;
    script.dataset.chartjs = '1';
    document.head.append(script);
  }
  script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter = {
  create(ctx) {
    const canvas = document.createElement('canvas');
    ctx.container.append(canvas);
    const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
    const toData = (d) => ({
      labels: d.categories,
      datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
    });
    let latest = ctx.getData();
    let instance = null;
    let dead = false;
    loadChartJs(() => {
      const Ctor = globalChart();
      if (dead || Ctor === undefined)
        return;
      instance = new Ctor(canvas, {
        type: kind,
        data: toData(latest),
        options: {
          responsive: true,
          maintainAspectRatio: false,
          indexAxis: ctx.type === 'bar' ? 'y' : 'x',
        },
      });
    });
    return {
      update(data) {
        latest = data;
        if (instance === null)
          return;
        const next = toData(data);
        instance.data.labels = next.labels;
        instance.data.datasets = next.datasets;
        instance.update();
      },
      destroy() {
        dead = true;
        instance?.destroy();
        canvas.remove();
      },
      resize() {
        instance?.resize();
      },
    };
  },
};
export const options = {
  rowKey: 'id',
  columns,
  rows,
  cellSelection: 'multiple',
  selection: 'multiple',
  ariaLabel: '지역별 분기 매출',
  chartAdapter: chartjsAdapter,
};
let host = null;
let chart = null;
function ensureHost() {
  if (host !== null)
    return host;
  const first = document.getElementById('grid');
  host = document.createElement('div');
  host.id = 'chart-host';
  host.style.cssText = 'height:260px;margin-top:10px';
  if (first !== null)
    first.after(host);
  else
    document.body.append(host);
  return host;
}
function cleanup() {
  chart?.destroy();
  chart = null;
}
export function setup(api, log) {
  const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
    log({
      ko: `차트를 만들었어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
      en: `Chart created: ${type}, ${categories} categories, ${series} series`,
    });
  });
  const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
    log({
      ko: `차트를 갱신했어요: ${type}, 분류 ${categories}개, 계열 ${series}개`,
      en: `Chart updated: ${type}, ${categories} categories, ${series} series`,
    });
  });
  log({
    ko: '지역과 1~3분기 칸을 끌어서 고른 뒤 버튼을 눌러요.',
    en: 'Drag-select the region and Q1..Q3 cells, then press a button.',
  });
  return () => {
    offCreated();
    offUpdated();
    cleanup();
    host?.remove();
    host = null;
  };
}
// 고른 칸이 없으면 앞의 네 행(지역~3분기)을 골라서 차트가 바로 나오게 해요.
function fromSelection(api, type) {
  if (api.getSelectedCells().length === 0)
    api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
  return api.createChart(ensureHost(), { source: 'selection', type });
}
export const actions = {
  fromSelection: (api) => {
    cleanup();
    chart = fromSelection(api, 'column');
  },
  allRows: (api) => {
    cleanup();
    chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
  },
  lineChart: (api) => {
    cleanup();
    chart = fromSelection(api, 'line');
  },
  clear: () => {
    cleanup();
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="fromSelection">Column chart from selection</button>
    <button type="button" id="allRows">All rows</button>
    <button type="button" id="lineChart">Line</button>
    <button type="button" id="clear">Clear</button>
  </div>
  <div id="grid" style="height: 320px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('fromSelection').addEventListener('click', () => actions.fromSelection(api));
document.getElementById('allRows').addEventListener('click', () => actions.allRows(api));
document.getElementById('lineChart').addEventListener('click', () => actions.lineChart(api));
document.getElementById('clear').addEventListener('click', () => actions.clear(api));
example.js
const rows = [
  { id: 1, region: 'Seoul', q1: 120, q2: 150, q3: 180, q4: 210, note: 'HQ' },
  { id: 2, region: 'Busan', q1: 90, q2: 110, q3: 140, q4: 130, note: 'Port' },
  { id: 3, region: 'Daegu', q1: 70, q2: 85, q3: 95, q4: 120, note: 'Inland' },
  { id: 4, region: 'Incheon', q1: 100, q2: 130, q3: 125, q4: 160, note: 'Airport' },
  { id: 5, region: 'Gwangju', q1: 60, q2: 75, q3: 90, q4: 80, note: 'Southwest' },
  { id: 6, region: 'Daejeon', q1: 80, q2: 95, q3: 110, q4: 140, note: 'Central' },
  { id: 7, region: 'Ulsan', q1: 110, q2: 105, q3: 150, q4: 170, note: 'Industrial' },
  { id: 8, region: 'Jeju', q1: 50, q2: 65, q3: 70, q4: 95, note: 'Tourism' },
];
const columns = [
  { id: 'region', title: 'Region', width: 110 },
  { id: 'q1', title: 'Q1 ($K)', kind: 'number', editable: true, width: 120 },
  { id: 'q2', title: 'Q2 ($K)', kind: 'number', editable: true, width: 120 },
  { id: 'q3', title: 'Q3 ($K)', kind: 'number', editable: true, width: 120 },
  { id: 'q4', title: 'Q4 ($K)', kind: 'number', editable: true, width: 120 },
  { id: 'note', title: 'Note', editable: true, width: 110 },
];
const CDN = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js';
function globalChart() {
  return window.Chart;
}
function loadChartJs(onReady) {
  if (globalChart() !== undefined) {
    onReady();
    return;
  }
  let script = document.querySelector('script[data-chartjs]');
  if (script === null) {
    script = document.createElement('script');
    script.src = CDN;
    script.dataset.chartjs = '1';
    document.head.append(script);
  }
  script.addEventListener('load', onReady, { once: true });
}
const chartjsAdapter = {
  create(ctx) {
    const canvas = document.createElement('canvas');
    ctx.container.append(canvas);
    const kind = { column: 'bar', bar: 'bar', line: 'line', area: 'line', pie: 'pie' }[ctx.type];
    const toData = (d) => ({
      labels: d.categories,
      datasets: d.series.map((s) => ({ label: s.name, data: s.values, fill: ctx.type === 'area' })),
    });
    let latest = ctx.getData();
    let instance = null;
    let dead = false;
    loadChartJs(() => {
      const Ctor = globalChart();
      if (dead || Ctor === undefined)
        return;
      instance = new Ctor(canvas, {
        type: kind,
        data: toData(latest),
        options: {
          responsive: true,
          maintainAspectRatio: false,
          indexAxis: ctx.type === 'bar' ? 'y' : 'x',
        },
      });
    });
    return {
      update(data) {
        latest = data;
        if (instance === null)
          return;
        const next = toData(data);
        instance.data.labels = next.labels;
        instance.data.datasets = next.datasets;
        instance.update();
      },
      destroy() {
        dead = true;
        instance?.destroy();
        canvas.remove();
      },
      resize() {
        instance?.resize();
      },
    };
  },
};
export const options = {
  rowKey: 'id',
  columns,
  rows,
  cellSelection: 'multiple',
  selection: 'multiple',
  ariaLabel: 'Regional sales by quarter',
  chartAdapter: chartjsAdapter,
};
let host = null;
let chart = null;
function ensureHost() {
  if (host !== null)
    return host;
  const first = document.getElementById('grid');
  host = document.createElement('div');
  host.id = 'chart-host';
  host.style.cssText = 'height:260px;margin-top:10px';
  if (first !== null)
    first.after(host);
  else
    document.body.append(host);
  return host;
}
function cleanup() {
  chart?.destroy();
  chart = null;
}
export function setup(api, log) {
  const offCreated = api.on('chartCreated', ({ type, categories, series }) => {
    log(`Chart created: ${type}, ${categories} categories, ${series} series`);
  });
  const offUpdated = api.on('chartUpdated', ({ type, categories, series }) => {
    log(`Chart updated: ${type}, ${categories} categories, ${series} series`);
  });
  log('Drag-select the region and Q1..Q3 cells, then press a button.');
  return () => {
    offCreated();
    offUpdated();
    cleanup();
    host?.remove();
    host = null;
  };
}
// With nothing selected, select the first four rows (region to Q3) so the chart appears right away.
function fromSelection(api, type) {
  if (api.getSelectedCells().length === 0)
    api.selectCells({ rowKey: 1, columnId: 'region' }, { rowKey: 4, columnId: 'q3' });
  return api.createChart(ensureHost(), { source: 'selection', type });
}
export const actions = {
  fromSelection: (api) => {
    cleanup();
    chart = fromSelection(api, 'column');
  },
  allRows: (api) => {
    cleanup();
    chart = api.createChart(ensureHost(), { source: 'all', type: 'column' });
  },
  lineChart: (api) => {
    cleanup();
    chart = fromSelection(api, 'line');
  },
  clear: () => {
    cleanup();
  },
};