UNPKG

canvas-grid-lines

Version:

Draws grid lines as HTML canvas element (baseline, squared and more)

211 lines (153 loc) 8.16 kB
# canvas-grid-lines ![npm](https://img.shields.io/npm/v/canvas-grid-lines.svg) ![license](https://img.shields.io/npm/l/canvas-grid-lines.svg) ![github-issues](https://img.shields.io/github/issues/profitlich-ch/canvas-grid-lines.svg) ! Draws grid lines as HTML canvas element (baseline, squared and more) ![stars](https://img.shields.io/github/stars/profitlich-ch/canvas-grid-lines.svg) ![forks](https://img.shields.io/github/forks/profitlich-ch/canvas-grid-lines.svg) ## Features - **Multiple grid types available**: - baseline (horizontal lines) - squared (horizontal and vertical lines) - columns (vertical lines showing columns with gaps) - rows (vertical lines for columns without gaps and horizontal lines) - **Retina/high res**: The grid is automatically adapted to the screen’s resolution and redrawn any time the window is resized. - **Crisp and precise**: The grid lines are set precisely onto the physical pixels of the screen thus they are always crisp. This distinguishes them from lines shown by SVG background images or drawn with CSS gradients. - **Column count updatable**: Already drawn grids may be updated with a new grid count. - **Self-placing**: A html `canvas` element will be added automatically to all html elements the script is applied to. If the given elements have no css `position`, `position: relative` will be added automatically. ## Demo Demo available at [https://profitlich-ch.github.io/canvas-grid-lines/](https://profitlich-ch.github.io/canvas-grid-lines/) ## Installation ``` npm install --save canvas-grid-lines ``` ## Usage The package supports modern ES Modules (ESM) for browsers and bundlers, legacy CommonJS (CJS) for Node.js, and comes with TypeScript types. ### Direct Browser / CDN Usage For simple HTML projects, you can use a CDN like unpkg or copy the JS and CSS file from the `dist/umd` folder. Add the following scripts and stylesheets to your HTML `<head>`: ```html <head> <!-- Load the stylesheet --> <link rel="stylesheet" href="[https://unpkg.com/canvas-grid-lines/dist/canvas-grid-lines.css](https://unpkg.com/canvas-grid-lines/dist/canvas-grid-lines.css)"> <!-- Load the script --> <script defer src="[https://unpkg.com/canvas-grid-lines/dist/umd/canvas-grid-lines.js](https://unpkg.com/canvas-grid-lines/dist/umd/canvas-grid-lines.js)"></script> </head> ``` Then, in a script tag before your closing `</body>` tag, you can access the library via the global canvasGridLines variable: ```html <script> document.addEventListener('DOMContentLoaded', () => { // The library is available globally canvasGridLines.initGrid({ targets: '[data-grid]', columns: 12 }); }); </script> ``` ### ES Modules / TypeScript ```javascript import { canvasGridLines, Units } from 'canvas-grid-lines'; import 'canvas-grid-lines/css'; document.addEventListener('DOMContentLoaded', () => { canvasGridLines.initGrid({ targets: '[data-grid]', columns: 12 }); }); ``` ### CommonJS (For Node.js or older build systems) ```javascript const { canvasGridLines, Units } = require('canvas-grid-lines'); canvasGridLines.initGrid({ targets: '[data-grid]', columns: 29 }); ``` CSS my be included either as an import in CSS/SCSS ```` @import "node_modules/canvas-grid-lines/dist/canvas-grid-lines.css"; ```` or in the HTML as `<link>` tag ``` <link rel="stylesheet" href="node_modules/canvas-grid-lines/dist/canvas-grid-lines.css"> ``` ### Prepare the HTML ```html <div class="my-container" data-grid-type="squared" data-grid-color="rgba(0, 0, 255, 0.5)"> ``` and for CommonJS ```html <link rel="stylesheet" href="canvas-grid-lines.css"> ``` ### Updating the columnCount You may change the column count of the grid any time. ```javascript canvasGridLines.setColumns(29); ``` ## Configuration ### How options are resolved Every option can be set in **two places** — the constructor's `options` object (or `initGrid`) **or** an HTML `data-grid-*` attribute on the container. The resolution order is: ``` options.X ?? container.getAttribute('data-grid-X') ?? default ``` **JS option > HTML attribute > default.** A value set in `initGrid({...})` is applied to **every** matched container and overrides per-element HTML attributes — be careful with globals. Rule of thumb: | Use… | When | |---|---| | `data-grid-*` HTML attribute | Value varies per container (`gridType`, `columns`, `color`, `termination`) | | JS option in `initGrid` | Value is global for all matched containers (`lineWidth`, `units`) | Example (matches the demo): ```javascript canvasGridLines.initGrid({ targets: '[data-grid-type]', lineWidth: 4, units: 'devicepixel', }); ``` ```html <div data-grid-type="baseline" data-grid-columns="47" data-grid-color="rgba(0,0,255,.5)"></div> <div data-grid-type="squared" data-grid-columns="40"></div> ``` ### HTML elements to be used Any `querySelectorAll`-compatible selector may be given. In the example code above the data attribute needed for the grid type is used. ### Grid Type The grid type is read from a mandatory data attribute `data-grid-type` and may be of the following values: `baseline`, `squared`, `columns`, `rows` ### Columns The `columns` configuration controls both the grid resolution **and** the line placement pattern. It accepts a number, a comma-separated string (used by the `data-grid-columns` HTML attribute) or a number array — and the expected number of values depends on the grid type: - `baseline`, `squared` — **1 value**: total grid columns. Example: `data-grid-columns="40"` / `columns: 40` - `columns` — **3 values**: `total, gap1, gap2`. Vertical lines are placed with alternating gaps. Example: `data-grid-columns="49,4,5"` produces lines at column 0, 4, 9, 13, 18, … (line · 4 · line · 5 · line · 4 · …). - `rows` — **5 values**: `total, v_gap1, v_gap2, h_gap1, h_gap2`. Vertical lines (column gaps) come first, horizontal lines (row gaps) second. Both share the same grid unit (`total`). Example: `data-grid-columns="30,4,5,5,6"`. If the number of values does not match the grid type, an error is thrown. All values must be positive integers. ### Line width Line width as integer or float. ### Units (optional, default: layoutPixel) The units parameter tells the script how to interpret the line width: either layout size (`layoutpixel` as in CSS) or physical pixels (`devicepixel`). ### Termination (optional, default: `shorten`) Controls how the grid terminates at the bottom edge. Settable via `data-grid-termination` or `{ termination }`. - `shorten` (default) — canvas height = parent height + 1 line width. Vertical lines stop at the last horizontal line (the bottom stub stays empty). - `fill` — same canvas height as `shorten`, but vertical lines run all the way down to the canvas edge. - `extend` — canvas is extended downward to the next multiple of `gridWidth / columns` so a horizontal bottom line can close the grid. No effect for `gridType: 'columns'` (no horizontal lines). ### Color (optional, default: black) A [CSS color value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value) setting the lines’ color. ### Init marker Once a grid has been created on a container, the container receives the attribute `data-grid-initialised="true"`. Use it as a CSS hook (e.g. to fade the container in only after the grid is drawn). ### Live updates After construction, `columns`, `gridType`, `color` and `lineWidth` can be reassigned directly on a `CanvasGridLines` instance — the grid re-renders automatically. Switching `gridType` re-derives the gap pattern from the current `columns`; if the value count no longer matches the new type, set a compatible `columns` first. ```javascript const grid = canvasGridLines.getGrid(myElement); grid.color = '#f00'; grid.lineWidth = 2; grid.columns = '20,2,3'; grid.gridType = 'columns'; ``` ## Development ### Tests Pure helpers (`parseColumns`, `validateColumns`, `gapPattern`, `GRID_TYPE_CONFIG`) are covered by Vitest. ``` npm test # single run npm run test:watch ``` ## License - **ISC** : http://opensource.org/licenses/ISC