### Install image-ascii-art Package Source: https://github.com/im-rises/image-ascii-art/blob/main/README.md Install the package using npm or yarn. ```bash npm install image-ascii-art ``` ```bash yarn add image-ascii-art ``` -------------------------------- ### getAsciiFromImage Function Source: https://context7.com/im-rises/image-ascii-art/llms.txt Converts raw `ImageData` to a plain ASCII string. It computes per-pixel luminance and maps it to a character from a provided character set. Darker pixels map to characters at the start of the string, and brighter pixels map to characters near the end. Returns a newline-delimited string. ```APIDOC ## `getAsciiFromImage` — Monochrome Pixel-to-ASCII Conversion ### Description Converts raw `ImageData` (from a canvas context) to a plain ASCII string by computing per-pixel luminance (`(R + G + B) / 3`) and mapping it to a character in the provided ASCII character set. Darker pixels map to characters at the start of the string; brighter pixels to characters near the end. Returns a newline-delimited string. ### Parameters - **`imageData`** (`ImageData`) - Required - The image data to convert. - **`asciiChars`** (`string`) - Required - A string of characters representing the grayscale ramp from dark to light. ### Returns - **`string`** - A newline-delimited string of ASCII characters representing the image. ``` -------------------------------- ### calculateAndSetFontSize Source: https://context7.com/im-rises/image-ascii-art/llms.txt Responsively adjusts the font size of a `
` element to ensure the ASCII text block perfectly fills a specified container dimensions. It iteratively increases the font size until the text fits, making the ASCII grid responsive to container size changes. ```APIDOC ## `calculateAndSetFontSize` — Responsive Font Sizing Iteratively increases the font size of a `` element (starting from 1px, in 0.1px steps) until the rendered text block exactly fills the given parent `width × height`. This ensures the ASCII grid always occupies the full container regardless of `charsPerLine` / `charsPerColumn` values. Called automatically by `` on mount and on every `ResizeObserver` event. ### Parameters - **preEl** (HTMLPreElement) - The ` ` element whose font size needs to be adjusted. - **charsPerLine** (number) - The number of characters per line in the ASCII art. - **charsPerColumn** (number) - The number of characters per column in the ASCII art. - **width** (number) - The target width of the container in pixels. - **height** (number) - The target height of the container in pixels. ### Returns - void ### Example ```ts import { calculateAndSetFontSize } from 'image-ascii-art/dist/canvas-handler/image-canvas-ascii'; const preEl = document.querySelector('pre')!; const parentEl = document.querySelector('#ascii-container')!; // Call once on load, and again whenever the container resizes calculateAndSetFontSize( preEl, 150, // charsPerLine 80, // charsPerColumn parentEl.clientWidth, // e.g. 1200 parentEl.clientHeight, // e.g. 640 ); // preEl.style.fontSize is now set to the largest value (in px) // at which all 150×80 characters fit within 1200×640 // Wire up to ResizeObserver for fully responsive behavior const ro = new ResizeObserver(([entry]) => { const { width, height } = entry.contentRect; calculateAndSetFontSize(preEl, 150, 80, width, height); }); ro.observe(parentEl); ``` ``` -------------------------------- ### Basic ImageAscii Component Usage Source: https://github.com/im-rises/image-ascii-art/blob/main/README.md Use the ImageAscii component with essential props to display ASCII art. Ensure the image is loaded before rendering. ```javascript``` -------------------------------- ### Default and Custom ASCII Character Palettes Source: https://context7.com/im-rises/image-ascii-art/llms.txt Provides the default character set for ASCII conversion, ordered by intensity. Demonstrates how to define and use custom palettes for different visual effects, such as block characters or classic dense sets. ```typescript // Default palette exported from the package const asciiChars = ' .,:;i1tfcLCXO0W@'; // ^ brightest ^ darkest // Custom palette example – block characters const blockChars = ' .:░▒▓█'; // Custom palette example – dense classic set const classicChars = 'Ñ@#W$9876543210?!abc;:+=-,._ '; // Pass a custom palette to the low-level helpers: import { getAsciiFromImage } from 'image-ascii-art/dist/canvas-handler/image-canvas-ascii'; const asciiText = getAsciiFromImage(imageData, blockChars); ``` -------------------------------- ### Import ImageAscii Component Source: https://github.com/im-rises/image-ascii-art/blob/main/README.md Import the ImageAscii component into your React project. ```javascript import {ImageAscii} from "image-ascii-art"; ``` -------------------------------- ### Using ArtTypeEnum for Rendering Modes in TypeScript Source: https://context7.com/im-rises/image-ascii-art/llms.txt Import and log the different rendering modes available in the ArtTypeEnum. These modes control how pixel color data is mapped to the ASCII output. ```typescript import { ArtTypeEnum } from 'image-ascii-art'; // ASCII – characters use a single fontColor / backgroundColor // ASCII_COLOR – each character wrapped in // ASCII_COLOR_BG_IMAGE – image set as backgroundImage on , color: transparent console.log(ArtTypeEnum.ASCII); console.log(ArtTypeEnum.ASCII_COLOR); console.log(ArtTypeEnum.ASCII_COLOR_BG_IMAGE); ``` -------------------------------- ### canvasImgToUrl Source: https://context7.com/im-rises/image-ascii-art/llms.txt Converts the current frame of an `HTMLCanvasElement` into an `HTMLImageElement` whose `src` is a base-64 data URL. This is used internally to apply the canvas image as a background for ASCII text, enabling CSS-based coloring. ```APIDOC ## `canvasImgToUrl` — Canvas Frame to Image URL Converts an `HTMLCanvasElement` to an `HTMLImageElement` whose `src` is a base-64 data URL of the current canvas frame. Used internally in `ASCII_COLOR_BG_IMAGE` mode to set the `backgroundImage` style of the `` element so characters are colored by the original image via CSS `background-clip: text`. ### Parameters - **canvas** (HTMLCanvasElement) - The canvas element to convert. ### Returns - (HTMLImageElement) - An image element with its `src` set to a data URL of the canvas content. ### Example ```ts import { canvasImgToUrl } from 'image-ascii-art/dist/canvas-handler/image-canvas-ascii'; const canvas = document.createElement('canvas'); canvas.width = 300; canvas.height = 200; const ctx = canvas.getContext('2d')!; const img = new Image(); img.src = '/my-photo.jpg'; img.onload = () => { ctx.drawImage(img, 0, 0, canvas.width, canvas.height); const snapshotImg = canvasImgToUrl(canvas); // snapshotImg.src === 'data:image/png;base64,iVBORw0KGgo...' // Apply as background to colorize ASCII text const pre = document.querySelector('pre')!; pre.style.backgroundImage = `url(${snapshotImg.src})`; pre.style.backgroundSize = '100% 100%'; pre.style.backgroundClip = 'text'; (pre.style as any).webkitBackgroundClip = 'text'; pre.style.color = 'transparent'; }; ``` ``` -------------------------------- ### ImageAscii Component with PreTag Reference Source: https://github.com/im-rises/image-ascii-art/blob/main/README.md Use the ImageAscii component with a preTagRef prop to access the generated ASCII text. This is useful for further manipulation or display. ```javascript``` -------------------------------- ### React Component for Image to ASCII Art Conversion Source: https://context7.com/im-rises/image-ascii-art/llms.txt This component integrates file uploads, image loading, aspect-ratio-preserving ASCII art generation, and clipboard copying. It uses ImageAscii with ASCII_COLOR_BG_IMAGE mode and FileReader for image loading. ```tsx import React, { useEffect, useRef, useState } from 'react'; import { ImageAscii, ArtTypeEnum } from 'image-ascii-art'; import defaultImage from './demoImage.png'; const ImageAsciiPanel = () => { const charsPerLine = 200; const [charsPerColumn, setCharsPerColumn] = useState(0); const [image, setImage] = useState (); const [ready, setReady] = useState(false); const preTagRef = useRef (null); const inputRef = useRef (null); const parentRef = useRef (null); const calcColumns = (img: HTMLImageElement) => Math.round(charsPerLine * (img.height / img.width)); // Load default image on mount useEffect(() => { const img = new Image(); img.src = defaultImage; img.onload = () => { setCharsPerColumn(calcColumns(img)); setImage(img); setReady(true); }; }, []); // Handle user file upload const handleImageChange = () => { const file = inputRef.current?.files?.[0]; if (!file) return; const reader = new FileReader(); reader.onload = () => { const img = new Image(); img.src = reader.result as string; img.onload = () => { setCharsPerColumn(calcColumns(img)); setImage(img); setReady(true); }; }; reader.readAsDataURL(file); }; const copyToClipboard = async () => { try { await navigator.clipboard.writeText(preTagRef.current!.innerText); console.log('Copied!'); } catch (err) { console.error('Copy failed:', err); } }; return ( <> {ready && image ? (> ); }; export default ImageAsciiPanel; ``` -------------------------------- ### ImageAscii Component for Responsive ASCII Art Source: https://context7.com/im-rises/image-ascii-art/llms.txt Use the ImageAscii component to render ASCII art from an HTMLImageElement. It handles responsive sizing based on a parent container and supports various rendering modes. Ensure the image is loaded before rendering. ```tsx import React, { useRef, useEffect, useState } from 'react'; import { ImageAscii, ArtTypeEnum } from 'image-ascii-art'; const MyAsciiViewer = () => { const parentRef = useRef) : No image loaded
}(null); const preTagRef = useRef (null); const [image, setImage] = useState (); const [ready, setReady] = useState(false); const charsPerLine = 150; const [charsPerColumn, setCharsPerColumn] = useState(0); useEffect(() => { const img = new Image(); img.src = '/my-photo.jpg'; img.onload = () => { // Maintain aspect ratio: columns = lines × (imgHeight / imgWidth) setCharsPerColumn(Math.round(charsPerLine * (img.height / img.width))); setImage(img); setReady(true); }; }, []); const copyAscii = async () => { if (preTagRef.current) { await navigator.clipboard.writeText(preTagRef.current.innerText); console.log('ASCII art copied to clipboard'); } }; return ( {ready && image ? (); }; export default MyAsciiViewer; ``` -------------------------------- ### Convert Image to Per-Character Color ASCII HTML Source: https://context7.com/im-rises/image-ascii-art/llms.txt Converts ImageData to an HTML string with each character colored individually. This method is visually accurate but can generate large DOM elements. Use for scenarios where visual fidelity is paramount. ```typescript import { getAsciiFromImageColor } from 'image-ascii-art/dist/canvas-handler/image-canvas-ascii'; const canvas = document.createElement('canvas'); canvas.width = 60; canvas.height = 30; const ctx = canvas.getContext('2d', { willReadFrequently: true })!; const img = new Image(); img.src = '/my-photo.jpg'; img.onload = () => { ctx.drawImage(img, 0, 0, canvas.width, canvas.height); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const asciiChars = ' .,:;i1tfcLCXO0W@'; const colorHtml = getAsciiFromImageColor(imageData, asciiChars); // Inject into a) : ( Loading image…
)}element const pre = document.getElementById('ascii-output') as HTMLPreElement; pre.innerHTML = colorHtml; // Each character looks like: @ }; ``` -------------------------------- ### getAsciiFromImageColor Source: https://context7.com/im-rises/image-ascii-art/llms.txt Converts ImageData to an HTML string where each character is wrapped in a span with its original pixel color. This method provides visual accuracy but can generate a large DOM. It's recommended to use `dangerouslySetInnerHTML` for injection. ```APIDOC ## `getAsciiFromImageColor` — Per-Character Color ASCII Conversion Converts `ImageData` to an HTML string where every character is wrapped in a `` tag, preserving the original pixel color. The resulting string must be injected via `dangerouslySetInnerHTML`. This mode is visually accurate but generates a large DOM; prefer `ASCII_COLOR_BG_IMAGE` for performance-sensitive use cases. ### Parameters - **imageData** (ImageData) - The image data to convert. - **asciiChars** (string) - A string of characters ordered from lightest to darkest, used for ASCII representation. ### Returns - (string) - An HTML string with colorized ASCII characters. ### Example ```ts import { getAsciiFromImageColor } from 'image-ascii-art/dist/canvas-handler/image-canvas-ascii'; // Assuming imageData is obtained from a canvas context const asciiChars = ' .,:;i1tfcLCXO0W@'; const colorHtml = getAsciiFromImageColor(imageData, asciiChars); // Inject into aelement const pre = document.getElementById('ascii-output') as HTMLPreElement; pre.innerHTML = colorHtml; // Each character looks like: @ ``` ``` -------------------------------- ### Monochrome Pixel-to-ASCII Conversion Source: https://context7.com/im-rises/image-ascii-art/llms.txt Use getAsciiFromImage to convert raw ImageData to a plain ASCII string. It maps pixel luminance to characters in a provided set. Ensure the ImageData is sampled from a canvas context. ```ts import { getAsciiFromImage } from 'image-ascii-art/dist/canvas-handler/image-canvas-ascii'; // Manually sample a canvas and convert to ASCII const canvas = document.createElement('canvas'); canvas.width = 80; // charsPerLine canvas.height = 40; // charsPerColumn const ctx = canvas.getContext('2d', { willReadFrequently: true })!; const img = new Image(); img.src = '/my-photo.jpg'; img.onload = () => { ctx.drawImage(img, 0, 0, canvas.width, canvas.height); const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); const asciiChars = ' .,:;i1tfcLCXO0W@'; // light → dark const asciiText = getAsciiFromImage(imageData, asciiChars); console.log(asciiText); // Output example (80 chars wide, 40 lines): // ....,,::;;iiiiiiiiiiiii11111tttttttttffffff... // ..,,;;i11ttffccLLCCXXOO00WW@@@@@@@@@@@@@@... // ... }; ``` -------------------------------- ### ImageAscii Component Source: https://context7.com/im-rises/image-ascii-art/llms.txt The primary exported React component for rendering ASCII art. It accepts an image element, parent container reference, rendering mode, grid dimensions, colors, and an optional ref for accessing the raw ASCII text. It handles canvas rendering and displays the ASCII art in a pre element. ```APIDOC ## `` Component ### Description The primary exported component. It accepts an `HTMLImageElement`, a reference to its parent container for responsive sizing, the desired rendering mode, grid dimensions (characters per line and column), colors, and an optional ` ` ref for accessing the raw ASCII text. It renders a hidden `