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

이미지: 크기·모양·불러오지 못했을 때Images: size, shape and load failures

cellRenderer 'image'는 셀 값(또는 map·src)을 주소로 이미지를 그려요. height로 크기를, shape로 모양을 정하고, 주소가 위험하거나 불러오지 못하면 fallback대로 비우거나 셀 글자를 보여요. onClick을 주면 이미지가 버튼이 돼요.cellRenderer 'image' draws an image from the cell value (or map and src). height sets the size and shape the outline; if the URL is unsafe or fails to load, fallback either leaves it empty or shows the cell text. With onClick the image becomes a button.

입문Beginner
직접 써 보기Live preview이미지: 크기·모양·불러오지 못했을 때Images: size, shape and load failures

코드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">
    <select aria-label="높이" id="height">
      <option value="20" selected>20px</option>
      <option value="28">28px</option>
      <option value="row">행 높이</option>
    </select>
  </div>
  <div id="grid" style="height: 200px"></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('height').addEventListener('change', (event) => actions.height(api, event.target.value));
example.js
// 예제는 네트워크 없이 동작하도록 그림을 캔버스로 만들어 data:image/png 주소로 써요(PNG·JPEG·GIF·WebP data 주소와 http(s)만 허용돼요).
function swatch(color, letter) {
  const canvas = document.createElement('canvas');
  canvas.width = 48;
  canvas.height = 48;
  const g = canvas.getContext('2d');
  if (g === null)
    return '';
  g.fillStyle = color;
  g.fillRect(0, 0, 48, 48);
  g.fillStyle = '#fff';
  g.font = 'bold 28px sans-serif';
  g.textAlign = 'center';
  g.textBaseline = 'middle';
  g.fillText(letter, 24, 26);
  return canvas.toDataURL('image/png');
}
const rows = [
  { id: 1, name: '김서연', photo: swatch('#1a56c4', '김') },
  { id: 2, name: '이준호', photo: swatch('#1a7f37', '이') },
  { id: 3, name: '위험한 주소', photo: 'javascript:alert(1)' },
  { id: 4, name: '불러오지 못함', photo: 'data:image/png;base64,AAAA' },
];
let log = () => undefined;
// src를 주지 않으면 셀 값이 주소예요. map({ 값: 주소 })이 있으면 그것을 먼저 봐요.
// height: 숫자(px)나 'row'(행 높이 - 4px), shape: 'round', fallback: 'text'는 실패했을 때 셀 글자를 보여요.
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 150 },
    {
      id: 'photo',
      title: '둥근 이미지',
      width: 130,
      cellRenderer: 'image',
      cellRendererParams: {
        shape: 'round',
        height: 20,
        fit: 'cover',
        alt: ({ row }) => `${row.name} 사진`,
        fallback: 'text',
        onClick: ({ rowKey }) => log({
          ko: `${String(rowKey)}번 이미지를 눌렀어요`,
          en: `Clicked the image of row ${String(rowKey)}`,
        }),
      },
      formatValue: (value) => String(value).startsWith('data:image/png;base64,AAAA') ? '없음' : '',
    },
    {
      id: 'square',
      key: 'photo', // 같은 필드를 한 번 더 보여 줘요
      title: '네모 이미지',
      width: 130,
      cellRenderer: 'image',
      cellRendererParams: { height: 20, fit: 'contain' },
    },
  ],
  rows,
  rowKey: 'id',
};
const columnsFor = (height) => (options.columns ?? []).map((column, index) => index === 0
  ? column
  : { ...column, cellRendererParams: { ...column.cellRendererParams, height } });
export function setup(api, write) {
  log = write;
  write({
    ko: '둥근 이미지를 눌러 보세요. 3번 줄은 위험한 주소라 그리지 않고, 4번 줄은 불러오지 못해 "없음"으로 바뀌어요.',
    en: 'Click a round image. Row 3 has an unsafe address so nothing is drawn, and row 4 fails to load and shows "없음" (none).',
  });
  return () => {
    log = () => undefined;
  };
}
export const actions = {
  height: (api, value) => api.setColumns(columnsFor(value === 'row' ? 'row' : Number(value) || 20)),
};

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">
    <select aria-label="Height" id="height">
      <option value="20" selected>20px</option>
      <option value="28">28px</option>
      <option value="row">Row height</option>
    </select>
  </div>
  <div id="grid" style="height: 200px"></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('height').addEventListener('change', (event) => actions.height(api, event.target.value));
example.js
// The example makes pictures on a canvas and uses data:image/png addresses so it works without a network (only PNG, JPEG, GIF and WebP data addresses and http(s) are allowed).
function swatch(color, letter) {
  const canvas = document.createElement('canvas');
  canvas.width = 48;
  canvas.height = 48;
  const g = canvas.getContext('2d');
  if (g === null)
    return '';
  g.fillStyle = color;
  g.fillRect(0, 0, 48, 48);
  g.fillStyle = '#fff';
  g.font = 'bold 28px sans-serif';
  g.textAlign = 'center';
  g.textBaseline = 'middle';
  g.fillText(letter, 24, 26);
  return canvas.toDataURL('image/png');
}
const rows = [
  { id: 1, name: 'Olivia Reed', photo: swatch('#1a56c4', 'O') },
  { id: 2, name: 'Liam Carter', photo: swatch('#1a7f37', 'L') },
  { id: 3, name: 'Unsafe address', photo: 'javascript:alert(1)' },
  { id: 4, name: 'Failed to load', photo: 'data:image/png;base64,AAAA' },
];
let log = () => undefined;
// Without src, the cell value is the address. If map ({ value: address }) is given, it is checked first.
// height: a number (px) or 'row' (row height - 4px), shape: 'round', fallback: 'text' shows the cell text on failure.
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 150 },
    {
      id: 'photo',
      title: 'Round image',
      width: 130,
      cellRenderer: 'image',
      cellRendererParams: {
        shape: 'round',
        height: 20,
        fit: 'cover',
        alt: ({ row }) => `Photo of ${row.name}`,
        fallback: 'text',
        onClick: ({ rowKey }) => log(`Clicked the image of row ${String(rowKey)}`),
      },
      formatValue: (value) => String(value).startsWith('data:image/png;base64,AAAA') ? 'none' : '',
    },
    {
      id: 'square',
      key: 'photo', // Shows the same field once more
      title: 'Square image',
      width: 130,
      cellRenderer: 'image',
      cellRendererParams: { height: 20, fit: 'contain' },
    },
  ],
  rows,
  rowKey: 'id',
};
const columnsFor = (height) => (options.columns ?? []).map((column, index) => index === 0
  ? column
  : { ...column, cellRendererParams: { ...column.cellRendererParams, height } });
export function setup(api, write) {
  log = write;
  write('Click a round image. Row 3 has an unsafe address so nothing is drawn, and row 4 fails to load and shows "none".');
  return () => {
    log = () => undefined;
  };
}
export const actions = {
  height: (api, value) => api.setColumns(columnsFor(value === 'row' ? 'row' : Number(value) || 20)),
};