### Complete Atrament Usage Example Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Demonstrates the full setup and usage of Atrament, including instance creation, event handling, and interactive controls for drawing, erasing, and changing properties. ```javascript import Atrament, { MODE_DRAW, MODE_ERASE, MODE_FILL } from 'atrament'; import fill from 'atrament/fill'; // Create instance const canvas = document.querySelector('#sketchpad'); const atrament = new Atrament(canvas, { width: 500, height: 500, color: '#000000', weight: 3, fill: fill }); // Event listeners atrament.addEventListener('dirty', () => { console.log('Canvas is now dirty'); }); atrament.addEventListener('strokestart', ({ x, y }) => { console.log(`Stroke started at (${x}, ${y})`); }); atrament.addEventListener('strokeend', ({ x, y }) => { console.log(`Stroke ended at (${x}, ${y})`); }); atrament.addEventListener('strokerecorded', ({ stroke }) => { console.log(`Recorded stroke with ${stroke.segments.length} segments`); // Store stroke for replay/undo/SVG export }); // Interactive controls document.getElementById('clearBtn').addEventListener('click', () => { atrament.clear(); }); document.getElementById('eraserBtn').addEventListener('click', () => { atrament.mode = MODE_ERASE; }); document.getElementById('drawBtn').addEventListener('click', () => { atrament.mode = MODE_DRAW; }); document.getElementById('colorPicker').addEventListener('change', (e) => { atrament.color = e.target.value; }); document.getElementById('weightSlider').addEventListener('input', (e) => { atrament.weight = parseFloat(e.target.value); }); // Enable stroke recording for undo/redo atrament.recordStrokes = true; ``` -------------------------------- ### Complete Fill Setup with Atrament Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Fill.md Initialize Atrament with the fill worker and set up UI controls for fill and draw modes, color picking, and undo functionality. This example demonstrates a full setup for using the fill module. ```javascript import Atrament, { MODE_FILL, MODE_DRAW } from 'atrament'; import fill from 'atrament/fill'; // Initialize with fill worker const canvas = document.querySelector('#sketchpad'); const atrament = new Atrament(canvas, { width: canvas.offsetWidth, height: canvas.offsetHeight, fill: fill }); // UI controls const fillButton = document.getElementById('fillBtn'); const drawButton = document.getElementById('drawBtn'); const fillColorPicker = document.getElementById('fillColor'); fillButton.addEventListener('click', () => { atrament.mode = MODE_FILL; fillButton.classList.add('active'); drawButton.classList.remove('active'); }); drawButton.addEventListener('click', () => { atrament.mode = MODE_DRAW; drawButton.classList.add('active'); fillButton.classList.remove('active'); }); fillColorPicker.addEventListener('change', (e) => { atrament.color = e.target.value; }); // Event handlers atrament.addEventListener('fillstart', ({ x, y }) => { console.log(`Fill started at (${x}, ${y})`); document.body.style.cursor = 'wait'; }); atrament.addEventListener('fillend', () => { console.log('Fill complete'); document.body.style.cursor = 'auto'; }); // Undo support (simple version) let fillHistory = []; atrament.addEventListener('fillstart', () => { fillHistory.push(canvas.toDataURL()); }); document.getElementById('undoBtn').addEventListener('click', () => { if (fillHistory.length > 0) { const previousState = fillHistory.pop(); const img = new Image(); img.onload = () => { atrament.clear(); const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); }; img.src = previousState; } }); ``` -------------------------------- ### Handle Events Early for Setup Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/events.md Listen to events like 'pointerdown' early in the event flow to adjust settings or perform setup before drawing actions begin. This allows for dynamic configuration based on input type. ```javascript atrament.addEventListener('pointerdown', (event) => { // Change settings before drawing starts if (event.pointerType === 'pen') { atrament.adaptiveStroke = false; } }); ``` -------------------------------- ### Install Atrament using npm Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/README.md Install the Atrament library using the Node Package Manager. ```bash npm install atrament ``` -------------------------------- ### Full Atrament configuration example Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/configuration.md Demonstrates setting all available configuration options during Atrament instance creation and how to change settings dynamically. ```javascript import Atrament, { MODE_DRAW } from 'atrament'; import fill from 'atrament/fill'; const canvas = document.querySelector('#sketchpad'); // Full configuration at creation const atrament = new Atrament(canvas, { // Canvas setup width: canvas.offsetWidth, height: canvas.offsetHeight, // Drawing settings color: '#2c3e50', weight: 4, mode: MODE_DRAW, // Smoothing and stroke smoothing: 0.9, adaptiveStroke: true, // Pressure sensitivity (for stylus/pen) pressureLow: 0.1, pressureHigh: 2.5, pressureSmoothing: 0.4, // Input handling secondaryMouseButton: true, // Allow eraser with right-click ignoreModifiers: false, // Recording recordStrokes: true, // Fill mode fill: fill }); // Change settings later document.getElementById('colorPicker').addEventListener('change', (e) => { atrament.color = e.target.value; }); document.getElementById('weightSlider').addEventListener('input', (e) => { atrament.weight = parseFloat(e.target.value); }); document.getElementById('smoothingSlider').addEventListener('input', (e) => { atrament.smoothing = parseFloat(e.target.value); }); ``` -------------------------------- ### Basic Atrament Setup Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/implementation-guide.md Initialize Atrament with a canvas element for immediate drawing. ```javascript import Atrament from 'atrament'; const canvas = document.querySelector('#sketchpad'); const atrament = new Atrament(canvas); // Start drawing immediately ``` -------------------------------- ### Initialize Atrament Without Fill Mode Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Fill.md Initialize Atrament without importing the fill module to reduce bundle size if fill functionality is not required. This example shows the minimal setup for Atrament when fill mode is not needed. ```javascript import Atrament from 'atrament'; const atrament = new Atrament(canvas); // fill mode is not available ``` -------------------------------- ### Atrament Setup with All Options Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/implementation-guide.md Configure Atrament with a comprehensive set of options including dimensions, color, weight, smoothing, and adaptive stroke. ```javascript import Atrament, { MODE_DRAW } from 'atrament'; import fill from 'atrament/fill'; const atrament = new Atrament(canvas, { width: canvas.offsetWidth, height: canvas.offsetHeight, color: '#000000', weight: 3, smoothing: 0.85, adaptiveStroke: true, secondaryMouseButton: true, ignoreModifiers: true, recordStrokes: true, fill: fill }); ``` -------------------------------- ### Queued Fill Operation Example Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Fill.md This example demonstrates how Atrament handles queued fill operations. If a fill is already in progress, a new fill request will be queued. ```javascript atrament.addEventListener('fillstart', ({ x, y }) => { console.log('Fill queued if another is in progress'); }); ``` -------------------------------- ### Initialize Atrament with Configuration Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Instantiate Atrament with a canvas element or selector and a configuration object. This example sets dimensions, color, weight, and includes a fill worker. ```javascript import Atrament from 'atrament'; import fill from 'atrament/fill'; const canvas = document.querySelector('#sketchpad'); const atrament = new Atrament(canvas, { width: 800, height: 600, color: '#000000', weight: 3, fill: fill }); ``` -------------------------------- ### Initialize Atrament with Custom Options Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/README.md Configure Atrament with specific dimensions, color, weight, and enable fill mode. Includes an example of switching to erase mode. ```javascript import Atrament, { MODE_DRAW, MODE_ERASE } from 'atrament'; import fill from 'atrament/fill'; const atrament = new Atrament(canvas, { width: 800, height: 600, color: '#000000', weight: 3, fill: fill }); document.getElementById('eraseBtn').onclick = () => { atrament.mode = MODE_ERASE; }; ``` -------------------------------- ### Setup Pointer Events Configuration Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/module-architecture.md Initializes pointer event listeners on a canvas, with options for filtering and preventing default behavior. Returns a cleanup function. ```javascript function setupPointerEvents(config, instance) { const { canvas, move, down, up } = config; const handlePointerMove = (event) => { // Filter non-primary pointers if (event.isPrimary === false) return; // Ignore secondary buttons if not enabled if (!instance.settings.ignoreSecondaryButtons && event.buttons !== 1) return; // Ignore modifier keys if enabled if (instance.settings.ignoreModifierKeys && (event.ctrlKey || event.metaKey || event.shiftKey)) return; event.preventDefault(); const rect = canvas.getBoundingClientRect(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; move({ x, y, event }); }; const handlePointerDown = (event) => { if (event.isPrimary === false) return; if (!instance.settings.ignoreSecondaryButtons && event.buttons !== 1) return; if (instance.settings.ignoreModifierKeys && (event.ctrlKey || event.metaKey || event.shiftKey)) return; event.preventDefault(); const rect = canvas.getBoundingClientRect(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; down({ x, y, event }); }; const handlePointerUp = (event) => { if (event.isPrimary === false) return; event.preventDefault(); const rect = canvas.getBoundingClientRect(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; up({ x, y, event }); }; canvas.addEventListener('pointermove', handlePointerMove); canvas.addEventListener('pointerdown', handlePointerDown); canvas.addEventListener('pointerup', handlePointerUp); canvas.addEventListener('pointerleave', handlePointerUp); // Treat leave as up return () => { canvas.removeEventListener('pointermove', handlePointerMove); canvas.removeEventListener('pointerdown', handlePointerDown); canvas.removeEventListener('pointerup', handlePointerUp); canvas.removeEventListener('pointerleave', handlePointerUp); }; } ``` -------------------------------- ### Handle Stroke Start Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/events.md The 'strokestart' event fires when a stroke begins, typically on pointer down. It provides the starting coordinates (x, y) of the stroke. This event fires after `pointerdown` and before any `draw()` calls. ```javascript atrament.addEventListener('strokestart', ({ x, y }) => { console.log(`Stroke started at (${x}, ${y})`); // Example: Update UI to show current position document.getElementById('positionDisplay').innerText = `(${x}, ${y})`; }); ``` -------------------------------- ### Complete Atrament Event Example Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/events.md Demonstrates how to listen to various Atrament events, including canvas state changes, stroke lifecycle events, fill operations, and pointer input. Includes basic UI integration for clearing and undoing. ```javascript import Atrament, { MODE_DRAW, MODE_ERASE, MODE_FILL } from 'atrament'; import fill from 'atrament/fill'; const canvas = document.querySelector('#sketchpad'); const atrament = new Atrament(canvas, { width: 800, height: 600, fill: fill, recordStrokes: true }); // Canvas state atrament.addEventListener('dirty', () => { console.log('✓ Canvas is dirty'); document.getElementById('clearBtn').disabled = false; }); atrament.addEventListener('clean', () => { console.log('✓ Canvas cleaned'); document.getElementById('clearBtn').disabled = true; }); // Stroke lifecycle atrament.addEventListener('strokestart', ({ x, y }) => { console.log(`↓ Stroke started at (${x}, ${y})`); }); atrament.addEventListener('segmentdrawn', ({ stroke }) => { console.log(`• Segment ${stroke.segments.length} drawn`); }); atrament.addEventListener('strokeend', ({ x, y }) => { console.log(`↑ Stroke ended at (${x}, ${y})`); }); atrament.addEventListener('strokerecorded', ({ stroke }) => { console.log(`✓ Stroke recorded: ${stroke.segments.length} segments`); // Save for undo/replay/export undoStack.push(stroke); }); // Fill operations atrament.addEventListener('fillstart', ({ x, y }) => { console.log(`⚙ Fill starting at (${x}, ${y})`); }); atrament.addEventListener('fillend', () => { console.log(`✓ Fill complete`); }); // Pointer input (for debugging) atrament.addEventListener('pointerdown', (event) => { console.log(`→ Pointer down: type=${event.pointerType}, pressure=${event.pressure}`); }); atrament.addEventListener('pointerup', (event) => { console.log(`← Pointer up`); }); // UI Integration document.getElementById('clearBtn').addEventListener('click', () => { atrament.clear(); }); document.getElementById('undoBtn').addEventListener('click', () => { if (undoStack.length > 0) { atrament.clear(); undoStack.pop(); // Discard current undoStack.forEach(stroke => replayStroke(atrament, stroke)); } }); ``` -------------------------------- ### Listen for Stroke Start Event Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/README.md Register an event listener to detect when a new stroke begins on the canvas, logging the starting coordinates. ```javascript atrament.addEventListener('strokestart', ({ x, y }) => { console.log(`Stroke started at (${x}, ${y})`); }); ``` -------------------------------- ### Update Settings Display on Stroke Start Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/implementation-guide.md Listen for the 'strokestart' event to update UI elements displaying the current drawing settings like color, weight, and smoothing. ```javascript function updateSettingsDisplay() { document.getElementById('colorDisplay').value = atrament.color; document.getElementById('weightDisplay').value = atrament.weight; document.getElementById('smoothingDisplay').value = atrament.smoothing; } atrament.addEventListener('strokestart', updateSettingsDisplay); ``` -------------------------------- ### Handle Fill Operation Start Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/events.md The 'fillstart' event fires when a fill operation begins in 'fill' mode, triggered by a pointer down event. It provides the coordinates (x, y) where the fill operation was initiated. This requires the 'fill' worker to be configured. ```javascript import { MODE_FILL } from 'atrament'; atrament.addEventListener('fillstart', ({ x, y }) => { console.log(`Fill operation started at (${x}, ${y})`); document.getElementById('fillIndicator').hidden = false; }); atrament.mode = MODE_FILL; ``` -------------------------------- ### Listen for Stroke Start/End Events Source: https://github.com/jakubfiala/atrament/blob/main/README.md Sets up event listeners to be notified when a stroke begins ('strokestart') and finishes ('strokeend'). These events provide the coordinates where the stroke started or ended. ```javascript sketchpad.addEventListener('strokestart', () => console.info('strokestart')); sketchpad.addEventListener('strokeend', () => console.info('strokeend')); ``` -------------------------------- ### Access and Modify Atrament Properties Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/configuration.md Use these examples to retrieve the current settings for color, weight, and mode, and to update these settings on an existing Atrament instance. Note that width, height, and fill cannot be modified after construction. ```javascript // Get current settings const currentColor = atrament.color; const currentWeight = atrament.weight; const currentMode = atrament.mode; // Modify settings atrament.color = '#ff0000'; atrament.weight = 5; atrament.mode = 'erase'; ``` -------------------------------- ### Listen for Fill Start/End Events Source: https://github.com/jakubfiala/atrament/blob/main/README.md Attaches event listeners for fill operations, which only fire in fill mode. The `fillstart` event includes the starting coordinates (x, y) of the fill operation. ```javascript sketchpad.addEventListener('fillstart', ({ x, y }) => console.info(`fillstart ${x} ${y}`), ); sketchpad.addEventListener('fillend', () => console.info('fillend')); ``` -------------------------------- ### Fill Verification: No-Op Example Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Fill.md Illustrates a fill operation that is skipped because the target pixel's color is identical to the selected fill color. This prevents unnecessary processing. ```javascript // If the fill color is the same as the start color, fill is skipped atrament.color = '#000000'; atrament.mode = 'fill'; // Click on a black pixel // No-op: already the fill color ``` -------------------------------- ### weight Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Gets or sets the current line thickness in pixels for the Atrament instance. The valid range for weight is from 1 to 100. ```APIDOC ## weight ### Description Gets or sets the current line thickness in pixels for the Atrament instance. The valid range for weight is from 1 to 100. ### Type `number` ### Example ```javascript // Get current weight const thickness = atrament.weight; // 2 // Set weight atrament.weight = 10; ``` ### Throws - **Error** - if value is not a number ``` -------------------------------- ### Using Fill Mode in Atrament Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Fill.md Configure Atrament with the fill worker and switch to fill mode. Event listeners are set up for fill start and end events. ```javascript import Atrament, { MODE_FILL } from 'atrament'; import fill from 'atrament/fill'; const atrament = new Atrament(canvas, { fill: fill }); // Switch to fill mode atrament.mode = MODE_FILL; // User clicks to fill atrament.addEventListener('fillstart', ({ x, y }) => { console.log(`Filling at (${x}, ${y})`); }); atrament.addEventListener('fillend', () => { console.log('Fill operation complete'); }); ``` -------------------------------- ### Get Smoothing Factor Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Calculates the smoothing factor based on the distance traveled. Use this to adjust stroke smoothness dynamically. ```javascript const distance = 50; const factor = atrament.getSmoothingFactor(distance); ``` -------------------------------- ### Main Methods Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/README.md Core methods for interacting with the Atrament instance, including drawing, clearing, and cleanup. ```APIDOC ## draw(x, y, prevX, prevY, pressure) ### Description Draws a segment of a stroke. This method is primarily for programmatic drawing. ### Method `draw` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **x** (number) - Required - The current X coordinate. - **y** (number) - Required - The current Y coordinate. - **prevX** (number) - Required - The previous X coordinate. - **prevY** (number) - Required - The previous Y coordinate. - **pressure** (number) - Optional - The pressure sensitivity of the input. ``` ```APIDOC ## clear() ### Description Clears the entire canvas, removing all drawings. ### Method `clear` ``` ```APIDOC ## beginStroke(x, y) ### Description Starts a new stroke programmatically. Use this when you need to manually control stroke initiation. ### Method `beginStroke` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **x** (number) - Required - The starting X coordinate of the stroke. - **y** (number) - Required - The starting Y coordinate of the stroke. ``` ```APIDOC ## endStroke(x, y) ### Description Ends the current stroke programmatically. Use this to finalize a manually started stroke. ### Method `endStroke` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **x** (number) - Required - The ending X coordinate of the stroke. - **y** (number) - Required - The ending Y coordinate of the stroke. ``` ```APIDOC ## destroy() ### Description Cleans up the Atrament instance, removing event listeners and freeing resources. Call this when the instance is no longer needed. ``` -------------------------------- ### Get Smoothing Factor Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Calculate the smoothing factor based on a given distance. This is an internal method but available for advanced usage. ```javascript getSmoothingFactor(distance) ``` -------------------------------- ### Instantiate Atrament with Constructor Configuration Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/configuration.md Pass a configuration object as the second argument to the Atrament constructor to set initial properties like width, height, color, weight, and fill worker. ```javascript import Atrament from 'atrament'; const atrament = new Atrament(canvas, { width: 800, height: 600, color: '#000000', weight: 3, fill: fillWorker }); ``` -------------------------------- ### Import Main Bundle (ESM) Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-surface.md Import the Atrament library using ECMAScript module syntax. ```javascript import Atrament from 'atrament'; // or import Atrament from 'atrament/dist/esm/index.js'; ``` -------------------------------- ### Initialize Atrament with Fill Mode Source: https://github.com/jakubfiala/atrament/blob/main/README.md Demonstrates how to import and inject the fill module into Atrament via the constructor for applications that require fill mode functionality. This helps reduce the main bundle size. ```javascript import Atrament from 'atrament'; import fill from 'atrament/fill'; const sketchpad = new Atrament({ fill }); ``` -------------------------------- ### Get Canvas Context Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Retrieve the 2D rendering context for the Atrament canvas element. This is useful for performing custom drawing operations. ```javascript const ctx = atrament.canvas.getContext('2d'); ``` -------------------------------- ### Import Main Bundle (CJS) Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-surface.md Import the Atrament library using CommonJS module syntax. ```javascript const Atrament = require('atrament'); // or const Atrament = require('atrament/dist/cjs/index.js'); ``` -------------------------------- ### smoothing Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Gets or sets the adaptive smoothing factor for strokes. Values range from 0 to 2, affecting line smoothness and responsiveness. ```APIDOC ## smoothing ### Description Gets or sets the adaptive smoothing factor for strokes. Values range from 0 to 2, affecting line smoothness and responsiveness. ### Type `number` ### Example ```javascript atrament.smoothing = 0.5; // More responsive, less smooth atrament.smoothing = 1.3; // Smoother, less responsive ``` ``` -------------------------------- ### mode Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Gets or sets the current drawing mode for the Atrament instance. Supported modes include 'draw', 'erase', 'fill', and 'disabled'. ```APIDOC ## mode ### Description Gets or sets the current drawing mode for the Atrament instance. Supported modes include 'draw', 'erase', 'fill', and 'disabled'. ### Type `string` ### Example ```javascript import { MODE_DRAW, MODE_ERASE, MODE_FILL, MODE_DISABLED } from 'atrament'; atrament.mode = MODE_DRAW; // Normal drawing atrament.mode = MODE_ERASE; // Eraser tool atrament.mode = MODE_FILL; // Flood fill tool atrament.mode = MODE_DISABLED; // No drawing, events still fire ``` ### Throws - **Error** - if mode is not one of the allowed modes ``` -------------------------------- ### Directory Structure of Atrament Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/module-architecture.md Illustrates the file organization within the Atrament source code, highlighting the main entry point, utility modules, and the fill sub-directory. ```bash src/ ├── index.js # Main Atrament class (1,043 lines) ├── constants.js # Configuration constants ├── events.js # Event handling system ├── mouse.js # Mouse/Point tracking ├── pixels.js # Pixel manipulation utilities ├── pointer-events.js # Pointer event setup ├── util.js # Utility functions └── fill/ ├── index.js # Fill worker export ├── worker.js # Worker entry point └── flood.js # Flood fill algorithm ``` -------------------------------- ### color Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Gets or sets the current stroke color for the Atrament instance. The color can be set using any valid CSS color string. ```APIDOC ## color ### Description Gets or sets the current stroke color for the Atrament instance. The color can be set using any valid CSS color string. ### Type `string` ### Example ```javascript // Get current color const currentColor = atrament.color; // 'rgba(0,0,0,1)' // Set color atrament.color = '#ff0000'; atrament.color = 'rgb(255, 0, 0)'; atrament.color = 'rgba(255, 0, 0, 0.5)'; ``` ### Throws - **Error** - if value is not a string ``` -------------------------------- ### Instantiate a Point object Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Point.md Create a new Point instance with specified x and y coordinates. This is the basic way to create a point object. ```javascript import { Point } from 'atrament'; const point = new Point(100, 200); console.log(point.x); // 100 console.log(point.y); // 200 ``` -------------------------------- ### Detect Tap Gesture Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/implementation-guide.md Identify tap gestures by checking the distance between the start and end points of a pointer event. This can be used for simple interactions like double-tap to erase. ```javascript let gestureStart = null; let gesturePoints = []; atrament.addEventListener('pointerdown', (event) => { gestureStart = { x: event.offsetX, y: event.offsetY }; gesturePoints = [gestureStart]; }); atrament.addEventListener('pointerup', (event) => { const gestureEnd = { x: event.offsetX, y: event.offsetY }; // Check for straight line gesture (double tap to erase?) const distance = Math.hypot( gestureEnd.x - gestureStart.x, gestureEnd.y - gestureStart.y ); if (distance < 50) { console.log('Tap gesture detected'); } }); ``` -------------------------------- ### Point Constructor Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Point.md Initializes a new Point object with specified x and y coordinates. ```APIDOC ## new Point(x, y) ### Description Initializes a new Point object with specified x and y coordinates. ### Parameters #### Path Parameters - **x** (number) - Required - X coordinate - **y** (number) - Required - Y coordinate ### Request Example ```javascript import { Point } from 'atrament'; const point = new Point(100, 200); console.log(point.x); // 100 console.log(point.y); // 200 ``` ``` -------------------------------- ### Real-time Drawing Preview Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/implementation-guide.md Sets up a canvas to capture drawing segments in real-time and updates a preview image. Listens for the 'segmentdrawn' event. ```javascript let previewCanvas = document.createElement('canvas'); previewCanvas.width = atrament.canvas.width; previewCanvas.height = atrament.canvas.height; atrament.addEventListener('segmentdrawn', () => { // Copy current drawing to preview const ctx = previewCanvas.getContext('2d'); ctx.drawImage(atrament.canvas, 0, 0); // Display preview document.getElementById('preview').src = previewCanvas.toDataURL(); }); ``` -------------------------------- ### Initialize Atrament Instance Source: https://github.com/jakubfiala/atrament/blob/main/README.md Create a new Atrament instance by passing the canvas element to the constructor. This sets up the drawing environment. ```javascript import Atrament from 'atrament'; const canvas = document.querySelector('#sketchpad'); const sketchpad = new Atrament(canvas); ``` -------------------------------- ### Get and Set Atrament Color Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Access the current stroke color of the Atrament instance or update it using CSS color strings. An error is thrown if an invalid string is provided. ```javascript // Get current color const currentColor = atrament.color; // 'rgba(0,0,0,1)' // Set color atrament.color = '#ff0000'; atrament.color = 'rgb(255, 0, 0)'; atrament.color = 'rgba(255, 0, 0, 0.5)'; ``` -------------------------------- ### Migrate Fill Import from v4 to v5 Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-surface.md Illustrates the change in how the fill module is imported and used between Atrament v4 and v5. ```javascript // v4 (fill bundled) import Atrament from 'atrament'; const atrament = new Atrament(canvas); atrament.mode = 'fill'; // Works if fill is available // v5 (fill separate) import Atrament from 'atrament'; import fill from 'atrament/fill'; const atrament = new Atrament(canvas, { fill }); atrament.mode = 'fill'; ``` -------------------------------- ### Import Optional Fill Module Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/README.md Import the optional fill module for Atrament. ```javascript import fill from 'atrament/fill'; ``` -------------------------------- ### Get and Set Atrament Weight Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Retrieve the current line thickness in pixels or set a new weight for strokes. The valid range for weight is 1 to 100. An error is thrown if the value is not a number. ```javascript // Get current weight const thickness = atrament.weight; // 2 // Set weight atrament.weight = 10; ``` -------------------------------- ### Initialize Atrament Canvas Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/types.md Instantiate Atrament with a canvas selector and configuration options. Available options include width, height, color, weight, and smoothing. ```javascript const atrament = new Atrament('#canvas', { width: 800, height: 600, color: '#ff0000', weight: 5, smoothing: 1.0 }); ``` -------------------------------- ### Instantiate Atrament Class Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-surface.md Create a new instance of the Atrament class, providing a canvas selector and optional configuration. ```javascript const atrament = new Atrament(selector, config); ``` -------------------------------- ### Undo/Redo Implementation Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/implementation-guide.md Implement undo and redo functionality using stacks to manage recorded strokes. Includes keyboard shortcut handling. ```javascript let undoStack = []; let redoStack = []; atrament.recordStrokes = true; atrament.addEventListener('strokerecorded', ({ stroke }) => { undoStack.push(stroke); redoStack = []; // Clear redo on new stroke }); function undo() { if (undoStack.length === 0) return; redoStack.push(undoStack.pop()); redrawCanvas(); } function redo() { if (redoStack.length === 0) return; undoStack.push(redoStack.pop()); redrawCanvas(); } function redrawCanvas() { atrament.clear(); undoStack.forEach(stroke => replayStroke(atrament, stroke)); } document.addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) { e.preventDefault(); undo(); } if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || (e.shiftKey && e.key === 'z'))) { e.preventDefault(); redo(); } }); ``` -------------------------------- ### Atrament Initialization Configuration Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-surface.md Configure Atrament during instantiation by providing an object with various properties such as dimensions, color, weight, smoothing, and mode. ```javascript new Atrament(canvas, { width: 800, // Canvas bitmap width height: 600, // Canvas bitmap height color: '#000000', // Initial stroke color weight: 3, // Initial line thickness smoothing: 0.85, // Smoothing factor adaptiveStroke: true, // Adaptive width mode: 'draw', // Initial mode secondaryMouseButton: false, // Right-click drawing ignoreModifiers: false, // Ignore modifiers pressureLow: 0, // Pressure lower bound pressureHigh: 2, // Pressure upper bound pressureSmoothing: 0.3, // Pressure filter recordStrokes: false, // Enable recording fill: undefined // Fill worker (optional) }) ``` -------------------------------- ### Import Default Atrament Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/README.md Import the default Atrament class for use in your project. ```javascript import Atrament from 'atrament'; ``` -------------------------------- ### Initialize Atrament with Options Source: https://github.com/jakubfiala/atrament/blob/main/README.md Initialize Atrament with specific width, height, and default color. This is useful for setting initial canvas properties and appearance. ```javascript const sketchpad = new Atrament(canvas, { width: 500, height: 500, color: 'orange', }); ``` -------------------------------- ### Configure Pressure Sensitivity Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/README.md Adjust the minimum and maximum thickness, and the smoothing factor for pressure sensitivity. ```javascript atrament.pressureLow = 0.2; // Minimum thickness atrament.pressureHigh = 2; // Maximum thickness atrament.pressureSmoothing = 0.4; ``` -------------------------------- ### Point Instance Method: set Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Point.md Updates both the x and y coordinates of the Point instance simultaneously. ```APIDOC ## set(x, y) ### Description Update both coordinates of the point. ### Parameters #### Path Parameters - **x** (number) - Required - New X coordinate - **y** (number) - Required - New Y coordinate ### Request Example ```javascript const point = new Point(0, 0); point.set(100, 200); console.log(point.x); // 100 console.log(point.y); // 200 // Update again point.set(50, 75); console.log(point.x); // 50 console.log(point.y); // 75 ``` ``` -------------------------------- ### Import Atrament with Mode Constants Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-surface.md Import the Atrament library along with its mode constants for use in your application. ```javascript import Atrament, { MODE_DRAW, MODE_ERASE, MODE_FILL, MODE_DISABLED } from 'atrament'; ``` -------------------------------- ### Initialize Atrament with Fill Worker Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Fill.md Pass the imported fill worker to the Atrament constructor to enable fill mode. Without this, fill mode will not be available. ```javascript import Atrament from 'atrament'; import fill from 'atrament/fill'; const atrament = new Atrament(canvas, { fill: fill // Pass the fill worker }); ``` -------------------------------- ### Atrament Instance Methods Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-surface.md Provides methods for programmatic control over drawing, canvas management, and event handling within an Atrament instance. ```APIDOC ## Instance Methods ### beginStroke - **Signature:** `(x: number, y: number) → void` - **Description:** Starts a new stroke at the specified coordinates. ### endStroke - **Signature:** `(x: number, y: number) → void` - **Description:** Ends the current stroke at the specified coordinates. ### draw - **Signature:** `(x, y, prevX, prevY, pressure?) → {x, y}` - **Description:** Draws a segment of the stroke, processing coordinates and pressure. Returns the processed coordinates. ### clear - **Signature:** `() → void` - **Description:** Clears the entire canvas content. ### getSmoothingFactor - **Signature:** `(distance: number) → number` - **Description:** Calculates and returns the smoothing factor based on the provided distance. ### destroy - **Signature:** `() → void` - **Description:** Cleans up resources and removes event listeners associated with the Atrament instance. ### addEventListener - **Signature:** `(event, handler) → void` - **Description:** Registers an event handler for a specific event. ### removeEventListener - **Signature:** `(event, handler) → void` - **Description:** Removes a previously registered event handler. ``` -------------------------------- ### Atrament Constructor Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/README.md Initializes a new Atrament instance. It takes a canvas selector or element and an optional configuration object. ```APIDOC ## new Atrament(selector, config) ### Description Initializes a new Atrament instance, enabling drawing capabilities on the specified HTML Canvas element. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **selector** (string | HTMLCanvasElement) - Required - A CSS selector string or the canvas element itself. - **config** (object) - Optional - Configuration options for Atrament. ``` -------------------------------- ### Drawing Flow Diagram Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/module-architecture.md Illustrates the sequence of events and method calls during a user's drawing action, from pointer down to stroke end. ```text User pointer down ↓ pointerdown event → pointerEventHandler() ↓ #pointerDown() method ├→ dispatchEvent('pointerdown') ├→ update #mouse position └→ beginStroke() if drawing mode └→ dispatchEvent('strokestart') User pointer moves ↓ pointermove event → pointerEventHandler() ↓ #pointerMove() method ├→ update #mouse position └→ draw() if mouse down and drawing mode ├→ smoothing calculation (uses lineDistance) ├→ adaptive stroke thickness adjustment ├→ canvas quadratic curve rendering ├→ stroke memory update (if recording) └→ dispatchEvent('segmentdrawn') User pointer up ↓ pointerup event → pointerEventHandler() ↓ #pointerUp() method ├→ dispatchEvent('pointerup') ├→ final draw() if touch ├→ endStroke() │ ├→ dispatchEvent('strokeend') │ └→ dispatchEvent('strokerecorded') if recording └→ reset #mouse state ``` -------------------------------- ### Enable Stroke Recording and Add Listener Source: https://github.com/jakubfiala/atrament/blob/main/README.md Enable stroke recording by setting `recordStrokes` to true and add an event listener for the `strokerecorded` event to store stroke data. ```javascript atrament.recordStrokes = true; atrament.addEventListener('strokerecorded', ({ stroke }) => { // store `stroke` somewhere }); ``` -------------------------------- ### Begin a Stroke Programmatically Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Initiate a new stroke at specified coordinates. This method is used for drawing strokes via code. ```javascript atrament.beginStroke(100, 100); ``` -------------------------------- ### beginStroke(x, y) Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md Begins a new stroke at the specified coordinates. This method is useful for programmatic drawing and initiates the stroke lifecycle. ```APIDOC ## Instance Methods ### `beginStroke(x, y)` Begin a stroke at the given coordinates. Used for programmatic drawing. ```javascript beginStroke(x, y) ``` #### Parameters | Parameter | Type | Description | |-----------|------|-------------| | x | number | X coordinate | | y | number | Y coordinate | #### Events Fires the `strokestart` event with `{ x, y }` data. #### Example ```javascript atrament.beginStroke(100, 100); ``` ``` -------------------------------- ### Main Properties Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/README.md Configurable properties of the Atrament instance that control drawing behavior and state. ```APIDOC ## color ### Description Gets or sets the current stroke color. Accepts CSS color values (e.g., '#FF0000', 'rgb(255,0,0)'). ### Property Type string ``` ```APIDOC ## weight ### Description Gets or sets the current line thickness (weight) for strokes. Accepts a numeric value. ### Property Type number ``` ```APIDOC ## mode ### Description Gets or sets the current drawing mode. Possible values are 'draw', 'erase', 'fill', 'disabled'. ### Property Type string ``` ```APIDOC ## smoothing ### Description Gets or sets the smoothing factor for strokes. A higher value results in smoother lines. Accepts a numeric value. ### Property Type number ``` ```APIDOC ## dirty ### Description Gets a boolean value indicating whether the canvas has unsaved content (i.e., has been drawn on since the last clear). ### Property Type boolean ``` ```APIDOC ## currentStroke ### Description Gets the currently in-progress stroke object, if stroke recording is enabled. This property is useful for accessing stroke data during drawing. ### Property Type object | null ``` -------------------------------- ### Configure Canvas Width and Height for High-DPI Displays Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/configuration.md Set the canvas width and height during construction to match the actual bitmap width for high-DPI/retina displays, using devicePixelRatio. ```javascript const canvas = document.querySelector('#sketchpad'); const atrament = new Atrament(canvas, { width: canvas.offsetWidth * window.devicePixelRatio, height: canvas.offsetHeight * window.devicePixelRatio }); ``` -------------------------------- ### Importing Fill Module Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/module-architecture.md Import the fill module, which is configured to be treated as a web worker by the build process. ```javascript import fill from 'atrament/fill' // → src/fill/index.js exports FillWorker // → webpack/rollup configured to treat as web-worker ``` -------------------------------- ### Configuration Properties Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Atrament.md These properties allow you to configure the Atrament drawing instance. They control aspects like pressure sensitivity, smoothing, mouse button usage, and modifier key handling. ```APIDOC ## Configuration Properties These properties allow you to configure the Atrament drawing instance. They control aspects like pressure sensitivity, smoothing, mouse button usage, and modifier key handling. ### `pressureHigh` **Type:** `number` Upper bound of the pressure sensitivity scale. At pressure = 1, line width is multiplied by this value. Default: `2`. ```javascript atrament.pressureHigh = 1; // No pressure variation atrament.pressureHigh = 2; // Up to 2x thickness at full pressure atrament.pressureHigh = 3; // Up to 3x thickness at full pressure ``` --- ### `pressureSmoothing` **Type:** `number` Low-pass filter amount for pressure values (0–1). Higher values smooth pressure input more, which may remove artifacts at stroke ends. Default: `0.3`. ```javascript atrament.pressureSmoothing = 0; // No filtering atrament.pressureSmoothing = 0.5; // Moderate filtering atrament.pressureSmoothing = 1; // Maximum filtering ``` --- ### `secondaryMouseButton` **Type:** `boolean` Allow drawing with the secondary (right) mouse button. Default: `false`. ```javascript atrament.secondaryMouseButton = true; // Allow right-click drawing ``` --- ### `ignoreModifiers` **Type:** `boolean` Ignore strokes when modifier keys (Alt, Ctrl, Cmd, Windows) are pressed. Default: `false`. ```javascript atrament.ignoreModifiers = true; // Modifiers prevent drawing ``` --- ### `canvas` **Type:** `HTMLCanvasElement` Reference to the canvas element. ```javascript const ctx = atrament.canvas.getContext('2d'); ``` --- ### `dirty` **Type:** `boolean` (read-only) Whether the canvas has been drawn on since the last clear. Updated automatically. ```javascript if (atrament.dirty) { console.log('Canvas has unsaved content'); } ``` --- ### `currentStroke` **Type:** `Stroke` (read-only) Data for the currently in-progress stroke. Only populated when `recordStrokes` is enabled. ```javascript atrament.addEventListener('segmentdrawn', () => { const stroke = atrament.currentStroke; console.log(`Segments so far: ${stroke.segments.length}`); }); ``` **Structure:** ```javascript { segments: [ { point: { x, y }, time, pressure }, // ... ], mode: 'draw', weight: 3, smoothing: 0.85, color: '#000000', adaptiveStroke: true } ``` ``` -------------------------------- ### Atrament Constructor Configuration Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-surface.md Configuration options that must be set when constructing a new Atrament instance. These options define the initial state and behavior of the drawing canvas. ```APIDOC ## Atrament Constructor ### Description Initializes a new Atrament instance with specified configuration options. ### Parameters #### Configuration Object - **width** (number) - Optional - Canvas bitmap width. - **height** (number) - Optional - Canvas bitmap height. - **color** (string) - Optional - Initial stroke color (e.g., '#000000'). - **weight** (number) - Optional - Initial line thickness. - **smoothing** (number) - Optional - Smoothing factor for strokes. - **adaptiveStroke** (boolean) - Optional - Enables adaptive stroke width. - **mode** (string) - Optional - Initial drawing mode (e.g., 'draw', 'erase', 'fill'). - **secondaryMouseButton** (boolean) - Optional - Enables drawing with the right mouse button. - **ignoreModifiers** (boolean) - Optional - Ignores modifier keys (e.g., Shift, Ctrl). - **pressureLow** (number) - Optional - Pressure lower bound for pressure sensitivity. - **pressureHigh** (number) - Optional - Pressure upper bound for pressure sensitivity. - **pressureSmoothing** (number) - Optional - Pressure filter smoothing factor. - **recordStrokes** (boolean) - Optional - Enables recording of strokes. - **fill** (Worker) - Optional - Fill worker instance for fill mode. ``` -------------------------------- ### Attempting Fill Mode Without Initialization Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/api-reference/Fill.md This code demonstrates the error that occurs when trying to use fill mode without passing the fill worker during Atrament initialization. ```javascript const atrament = new Atrament(canvas); atrament.mode = 'fill'; // Error: "atrament: fill mode only works if the fillWorker option // is passed to the Atrament constructor" ``` -------------------------------- ### Enable Undo/Redo Functionality Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/README.md Configure Atrament to record strokes for undo/redo operations. Strokes are stored in an array and replayed when undoing. ```javascript atrament.recordStrokes = true; let undoStack = []; atrament.addEventListener('strokerecorded', ({ stroke }) => { undoStack.push(stroke); }); function undo() { atrament.clear(); undoStack.pop(); undoStack.forEach(stroke => replayStroke(atrament, stroke)); } ``` -------------------------------- ### Export Stroke Data to Local Storage Source: https://github.com/jakubfiala/atrament/blob/main/_autodocs/README.md Enable stroke recording and export individual stroke data as JSON to local storage. ```javascript atrament.recordStrokes = true; atrament.addEventListener('strokerecorded', ({ stroke }) => { // stroke has segments: [{ point: {x, y}, time, pressure }] const json = JSON.stringify(stroke); localStorage.setItem('myStroke', json); }); ```