Skip to content

ImageGrid

ImageGrid renders a rectangular grid of images with canvas. It is intended for large grids where creating one DOM or SVG node per cell would be too expensive.

The component is a plain DOM canvas and does not add default classes or styles.

Import

ts
import { ImageGrid } from '@putianyi888/vue3-plots'

Example

vue
<template>
    <ImageGrid
        :cell-height="16"
        :cell-width="16"
        :cells="cells"
        :images="images"
    />
</template>

<script setup lang="ts">
import { ImageGrid } from '@putianyi888/vue3-plots'

const cells = [
    ['grass', 'water', 'grass'],
    ['stone', 'grass', 'water'],
]
const images = {
    grass: createTile('#86efac'),
    stone: createTile('#d4d4d8'),
    water: createTile('#93c5fd'),
}

function createTile(color: string) {
    const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" fill="${color}"/></svg>`

    return `data:image/svg+xml,${encodeURIComponent(svg)}`
}
</script>

Props

PropTypeDefaultDescription
cellsstring[][]RequiredTwo-dimensional grid of image keys.
imagesRecord<string, string>RequiredMap from image keys used in cells to image URLs.
cellWidthnumberRequiredWidth of each rendered cell in canvas pixels.
cellHeightnumberRequiredHeight of each rendered cell in canvas pixels.

Exposed

ExposedTypeDescription
cellIndexCellIndexCurrent mouse position as cell indexes. Undefined when the mouse is outside a valid cell.

Notes

cells is a two-dimensional array of image keys. images maps those keys to image URLs. Missing keys are skipped.

If the grid is small, a regular CSS grid with <img> elements is usually simpler and more flexible. Use ImageGrid when the grid is large enough that many DOM nodes become expensive.

Images are pre-rendered to offscreen canvases using cell-width and cell-height, then copied into the visible canvas for each matching cell.

ImageGrid deep-watches cells, so changing a key inside the two-dimensional array triggers a redraw.

Use a template ref to read the exposed cellIndex, which contains the current mouse position as { rowIndex, columnIndex }. It is undefined when the mouse is outside a valid cell.