이미지: 크기·모양·불러오지 못했을 때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.
코드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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));// 예제는 네트워크 없이 동작하도록 그림을 캔버스로 만들어 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)),
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>이미지: 크기·모양·불러오지 못했을 때</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제는 네트워크 없이 동작하도록 그림을 캔버스로 만들어 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'는 실패했을 때 셀 글자를 보여요.
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 } });
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;
};
}
const actions = {
height: (api, value) => api.setColumns(columnsFor(value === 'row' ? 'row' : Number(value) || 20)),
};
options.ariaLabel = "이미지: 크기·모양·불러오지 못했을 때";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('height').addEventListener('change', (event) => actions.height(api, event.target.value));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="높이"
disabled={!api}
onChange={(event) => api && actions.height(api, event.target.value)}
>
<option value="20">20px</option>
<option value="28">28px</option>
<option value="row">행 높이</option>
</select>
</div>
<Grid style={{ height: 200 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
photo: string;
}
// 예제는 네트워크 없이 동작하도록 그림을 캔버스로 만들어 data:image/png 주소로 써요(PNG·JPEG·GIF·WebP data 주소와 http(s)만 허용돼요).
function swatch(color: string, letter: string): string {
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: Row[] = [
{ 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: (message: LogText) => void = () => undefined;
// src를 주지 않으면 셀 값이 주소예요. map({ 값: 주소 })이 있으면 그것을 먼저 봐요.
// height: 숫자(px)나 'row'(행 높이 - 4px), shape: 'round', fallback: 'text'는 실패했을 때 셀 글자를 보여요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 150 },
{
id: 'photo',
title: '둥근 이미지',
width: 130,
cellRenderer: 'image',
cellRendererParams: {
shape: 'round',
height: 20,
fit: 'cover',
alt: ({ row }: { row: unknown }) => `${(row as Row).name} 사진`,
fallback: 'text',
onClick: ({ rowKey }: { rowKey: unknown }) =>
log({
ko: `${String(rowKey)}번 이미지를 눌렀어요`,
en: `Clicked the image of row ${String(rowKey)}`,
}),
},
formatValue: (value: unknown) =>
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: number | 'row') =>
(options.columns ?? []).map((column, index) =>
index === 0
? column
: { ...column, cellRendererParams: { ...(column.cellRendererParams as object), height } },
);
export function setup(api: GridApi<Row>, write: (message: LogText) => void) {
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: GridApi<Row>, value?: string) =>
api.setColumns(columnsFor(value === 'row' ? 'row' : Number(value) || 20) as never),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="높이"
:disabled="!api"
@change="api && actions.height(api, ($event.target as HTMLSelectElement).value)"
>
<option value="20" selected>20px</option>
<option value="28">28px</option>
<option value="row">행 높이</option>
</select>
</div>
<Grid style="height: 200px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
photo: string;
}
// 예제는 네트워크 없이 동작하도록 그림을 캔버스로 만들어 data:image/png 주소로 써요(PNG·JPEG·GIF·WebP data 주소와 http(s)만 허용돼요).
function swatch(color: string, letter: string): string {
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: Row[] = [
{ 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: (message: LogText) => void = () => undefined;
// src를 주지 않으면 셀 값이 주소예요. map({ 값: 주소 })이 있으면 그것을 먼저 봐요.
// height: 숫자(px)나 'row'(행 높이 - 4px), shape: 'round', fallback: 'text'는 실패했을 때 셀 글자를 보여요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 150 },
{
id: 'photo',
title: '둥근 이미지',
width: 130,
cellRenderer: 'image',
cellRendererParams: {
shape: 'round',
height: 20,
fit: 'cover',
alt: ({ row }: { row: unknown }) => `${(row as Row).name} 사진`,
fallback: 'text',
onClick: ({ rowKey }: { rowKey: unknown }) =>
log({
ko: `${String(rowKey)}번 이미지를 눌렀어요`,
en: `Clicked the image of row ${String(rowKey)}`,
}),
},
formatValue: (value: unknown) =>
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: number | 'row') =>
(options.columns ?? []).map((column, index) =>
index === 0
? column
: { ...column, cellRendererParams: { ...(column.cellRendererParams as object), height } },
);
export function setup(api: GridApi<Row>, write: (message: LogText) => void) {
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: GridApi<Row>, value?: string) =>
api.setColumns(columnsFor(value === 'row' ? 'row' : Number(value) || 20) as never),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<select
aria-label="높이"
[disabled]="!api"
(change)="api && actions.height(api, $any($event.target).value)"
>
<option value="20" selected>20px</option>
<option value="28">28px</option>
<option value="row">행 높이</option>
</select>
</div>
<mx-grid style="height: 200px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
photo: string;
}
// 예제는 네트워크 없이 동작하도록 그림을 캔버스로 만들어 data:image/png 주소로 써요(PNG·JPEG·GIF·WebP data 주소와 http(s)만 허용돼요).
function swatch(color: string, letter: string): string {
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: Row[] = [
{ 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: (message: LogText) => void = () => undefined;
// src를 주지 않으면 셀 값이 주소예요. map({ 값: 주소 })이 있으면 그것을 먼저 봐요.
// height: 숫자(px)나 'row'(행 높이 - 4px), shape: 'round', fallback: 'text'는 실패했을 때 셀 글자를 보여요.
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 150 },
{
id: 'photo',
title: '둥근 이미지',
width: 130,
cellRenderer: 'image',
cellRendererParams: {
shape: 'round',
height: 20,
fit: 'cover',
alt: ({ row }: { row: unknown }) => `${(row as Row).name} 사진`,
fallback: 'text',
onClick: ({ rowKey }: { rowKey: unknown }) =>
log({
ko: `${String(rowKey)}번 이미지를 눌렀어요`,
en: `Clicked the image of row ${String(rowKey)}`,
}),
},
formatValue: (value: unknown) =>
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: number | 'row') =>
(options.columns ?? []).map((column, index) =>
index === 0
? column
: { ...column, cellRendererParams: { ...(column.cellRendererParams as object), height } },
);
export function setup(api: GridApi<Row>, write: (message: LogText) => void) {
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: GridApi<Row>, value?: string) =>
api.setColumns(columnsFor(value === 'row' ? 'row' : Number(value) || 20) as never),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<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>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));// 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)),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Images: size, shape and load failures</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 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.
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 } });
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;
};
}
const actions = {
height: (api, value) => api.setColumns(columnsFor(value === 'row' ? 'row' : Number(value) || 20)),
};
options.ariaLabel = "Images: size, shape and load failures";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('height').addEventListener('change', (event) => actions.height(api, event.target.value));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="Height"
disabled={!api}
onChange={(event) => api && actions.height(api, event.target.value)}
>
<option value="20">20px</option>
<option value="28">28px</option>
<option value="row">Row height</option>
</select>
</div>
<Grid style={{ height: 200 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
photo: string;
}
// 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: string, letter: string): string {
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: Row[] = [
{ 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: (message: LogText) => void = () => 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: GridOptions<Row> = {
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 }: { row: unknown }) => `Photo of ${(row as Row).name}`,
fallback: 'text',
onClick: ({ rowKey }: { rowKey: unknown }) =>
log(`Clicked the image of row ${String(rowKey)}`),
},
formatValue: (value: unknown) =>
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: number | 'row') =>
(options.columns ?? []).map((column, index) =>
index === 0
? column
: { ...column, cellRendererParams: { ...(column.cellRendererParams as object), height } },
);
export function setup(api: GridApi<Row>, write: (message: LogText) => void) {
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: GridApi<Row>, value?: string) =>
api.setColumns(columnsFor(value === 'row' ? 'row' : Number(value) || 20) as never),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="Height"
:disabled="!api"
@change="api && actions.height(api, ($event.target as HTMLSelectElement).value)"
>
<option value="20" selected>20px</option>
<option value="28">28px</option>
<option value="row">Row height</option>
</select>
</div>
<Grid style="height: 200px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
photo: string;
}
// 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: string, letter: string): string {
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: Row[] = [
{ 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: (message: LogText) => void = () => 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: GridOptions<Row> = {
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 }: { row: unknown }) => `Photo of ${(row as Row).name}`,
fallback: 'text',
onClick: ({ rowKey }: { rowKey: unknown }) =>
log(`Clicked the image of row ${String(rowKey)}`),
},
formatValue: (value: unknown) =>
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: number | 'row') =>
(options.columns ?? []).map((column, index) =>
index === 0
? column
: { ...column, cellRendererParams: { ...(column.cellRendererParams as object), height } },
);
export function setup(api: GridApi<Row>, write: (message: LogText) => void) {
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: GridApi<Row>, value?: string) =>
api.setColumns(columnsFor(value === 'row' ? 'row' : Number(value) || 20) as never),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<select
aria-label="Height"
[disabled]="!api"
(change)="api && actions.height(api, $any($event.target).value)"
>
<option value="20" selected>20px</option>
<option value="28">28px</option>
<option value="row">Row height</option>
</select>
</div>
<mx-grid style="height: 200px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
photo: string;
}
// 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: string, letter: string): string {
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: Row[] = [
{ 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: (message: LogText) => void = () => 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: GridOptions<Row> = {
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 }: { row: unknown }) => `Photo of ${(row as Row).name}`,
fallback: 'text',
onClick: ({ rowKey }: { rowKey: unknown }) =>
log(`Clicked the image of row ${String(rowKey)}`),
},
formatValue: (value: unknown) =>
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: number | 'row') =>
(options.columns ?? []).map((column, index) =>
index === 0
? column
: { ...column, cellRendererParams: { ...(column.cellRendererParams as object), height } },
);
export function setup(api: GridApi<Row>, write: (message: LogText) => void) {
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: GridApi<Row>, value?: string) =>
api.setColumns(columnsFor(value === 'row' ? 'row' : Number(value) || 20) as never),
};