Skip to content

laat/chess-board

Repository files navigation

<chess-board> npm

A web component for displaying chess positions.

Demo

Check it live.

Install

npm install chess-board

Usage

Import the module once to register the <chess-board> custom element:

import "chess-board";

Then use it in your markup. The element reads its initial position from its text content as a FEN string (the piece-placement field is enough):

<chess-board>rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR</chess-board>

Changing the text content later updates the board — it's observed via a MutationObserver.

TypeScript

Types for the element, squares and pieces are exported from the package:

import type { ChessBoardElement, Square, Piece } from "chess-board";

Attributes

Attribute Description
unicode Render pieces as Unicode glyphs instead of the default SVGs.
frame Show file (a–h) and rank (1–8) labels around the board.
reverse Flip the board so the black pieces are on the bottom.
<chess-board unicode frame reverse>
  rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
</chess-board>

Properties

fen (get / set)

Read or write the current position as a FEN string.

const board = document.querySelector("chess-board");

board.fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR";
board.move("e2", "e4");

const currentFen = board.fen;

Methods

All methods operate on an already-mounted element. Grab it with document.querySelector — do not use new:

const board = document.querySelector("chess-board");

piece(square)

Return the piece on the given square, or an empty string if the square is empty.

board.piece("e1"); // "K"
board.piece("e4"); // ""

put(square, piece)

Place a piece on a square.

board.put("a4", "Q"); // white queen on a4

clear(square)

Remove the piece from a square.

board.clear("a4");

move(from, to)

Move a piece between squares.

board.move("e2", "e4");

clearBoard()

Remove all pieces from the board.

board.clearBoard();

Pieces

Pieces use Forsyth–Edwards Notation: uppercase letters are white, lowercase are black.

P // ♙ white pawn
N // ♘ white knight
B // ♗ white bishop
R // ♖ white rook
Q // ♕ white queen
K // ♔ white king

p // ♟ black pawn
n // ♞ black knight
b // ♝ black bishop
r // ♜ black rook
q // ♛ black queen
k // ♚ black king

License

MIT © Sigurd Fosseng

About

A Web Component for displaying chess positions

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors