### Konva Designer: Page Settings and Styling Source: https://context7.com/xachary/konva-designer-sample/llms.txt Demonstrates how to retrieve and update global page settings in Konva Designer, such as background color, default stroke, fill, and text properties. Includes examples of using default settings and listening for page settings changes. Requires `Render` import. ```typescript import { Render } from './Render' // Get current page settings const pageSettings = render.getPageSettings() console.log('Background:', pageSettings.background) console.log('Default stroke:', pageSettings.stroke) console.log('Default fill:', pageSettings.fill) // Update page settings render.setPageSettings({ background: 'rgb(240,240,240)', stroke: 'rgb(0,0,0)', strokeWidth: 2, fill: 'rgb(255,255,255)', linkStroke: 'rgb(100,100,100)', linkStrokeWidth: 2, fontSize: 16, textFill: 'rgb(0,0,0)' }, true) // true = update history // Use default settings const defaultSettings = Render.PageSettingsDefault console.log('Defaults:', defaultSettings) // Listen to page settings changes render.on('page-settings-change', (settings) => { console.log('Page settings updated:', settings) }) // Update background color only const background = render.getBackground() if (background) { background.fill('rgb(255,255,255)') } render.updateBackground() ``` -------------------------------- ### Get and Manipulate Stage State (TypeScript) Source: https://context7.com/xachary/konva-designer-sample/llms.txt Retrieve the current state of the canvas stage, including dimensions, scale, and pan position. Allows for manual adjustment of stage scale and position, followed by a redraw to apply changes. Useful for fine-grained control over the canvas view. ```typescript // Get stage state const state = render.getStageState() console.log('Canvas size:', state.width, 'x', state.height) console.log('Current scale:', state.scale) console.log('Pan position:', state.x, state.y) // Manual zoom and pan render.stage.scale({ x: 1.5, y: 1.5 }) render.stage.position({ x: -100, y: -100 }) render.redraw() ``` -------------------------------- ### Initialize Konva Render Instance with Options Source: https://context7.com/xachary/konva-designer-sample/llms.txt Demonstrates how to initialize the main Konva Render instance, configuring canvas dimensions and various visual and functional features. It sets up event listeners for selection and history changes, and includes dynamic resizing. ```typescript import { Render } from './Render' // Initialize the designer canvas const stageElement = document.getElementById('stage-container')! const render = new Render(stageElement, { width: 1920, height: 1080, // Visual features showBg: true, showRuler: true, showRefLine: true, showPreview: true, showContextmenu: true, // Magnetic snapping attractResize: true, attractBg: true, attractNode: true, // Mode readonly: false }) // Listen to events render.on('selection-change', (nodes) => { console.log('Selected nodes:', nodes.map(n => n.id())) }) render.on('history-change', ({ records, index }) => { console.log(`History: ${index + 1}/${records.length}`) }) // Resize canvas dynamically window.addEventListener('resize', () => { render.resize(window.innerWidth, window.innerHeight) }) ``` -------------------------------- ### Konva Designer: Alignment and Distribution Source: https://context7.com/xachary/konva-designer-sample/llms.txt Illustrates how to align and distribute multiple selected Konva nodes using the designer's alignment tools. This includes aligning edges, centers, and distributing elements with equal spacing. Magnetic snapping can also be enabled. ```typescript // Select multiple nodes for alignment const nodes = [ render.layer.findOne('#icon-1'), render.layer.findOne('#photo-1'), render.layer.findOne('#gif-1') ] render.selectionTool.select(nodes) // Align left edges render.alignTool.alignLeft() // Align right edges render.alignTool.alignRight() // Align top edges render.alignTool.alignTop() // Align bottom edges render.alignTool.alignBottom() // Align horizontal centers render.alignTool.alignCenterX() // Align vertical centers render.alignTool.alignCenterY() // Distribute horizontally with equal spacing render.alignTool.distributeX() // Distribute vertically with equal spacing render.alignTool.distributeY() // Magnetic snapping tool for automatic alignment during drag render.attractTool.enabled = true render.attractTool.threshold = 5 // pixels render.updateHistory() render.redraw() ``` -------------------------------- ### Konva Designer: Copy, Paste, and Layer Management Source: https://context7.com/xachary/konva-designer-sample/llms.txt Demonstrates how to copy, paste, and reorder selected elements using the Konva Designer's tools. Includes methods for moving elements to top, bottom, up, down, and positioning utilities. Requires the `render` object to be initialized. ```typescript // Copy selected nodes render.copyTool.copy() // Paste at specific position const pastedNodes = await render.copyTool.paste({ x: 400, y: 400 }) console.log('Pasted nodes:', pastedNodes.map(n => n.id())) // Move selected nodes to top render.zIndexTool.toTop() // Move selected nodes to bottom render.zIndexTool.toBottom() // Move selected nodes one layer up render.zIndexTool.up() // Move selected nodes one layer down render.zIndexTool.down() // Position utilities render.positionTool.moveUp(10) // Move up by 10 pixels render.positionTool.moveDown(10) render.positionTool.moveLeft(10) render.positionTool.moveRight(10) // Center nodes in viewport render.positionTool.center() render.updateHistory() ``` -------------------------------- ### Load and Add Various Assets to Konva Canvas Source: https://context7.com/xachary/konva-designer-sample/llms.txt Shows how to load different asset types including SVG, images, animated GIFs, and JSON compositions using the `assetTool`. Each loaded asset is configured with attributes like ID, name, position, and made draggable before being added to the Konva layer. It also includes steps for adding connection points and updating the render history. ```typescript import * as Types from './Render/types' // Load SVG asset const svgGroup = await render.assetTool.loadSvg('./assets/icon.svg') svgGroup.setAttrs({ id: 'icon-1', name: 'asset', x: 100, y: 100, draggable: true }) render.layer.add(svgGroup) // Load regular image const imgNode = await render.assetTool.loadImg('./assets/photo.png') const imgGroup = new Konva.Group({ id: 'photo-1', name: 'asset', x: 300, y: 100, draggable: true }) imgGroup.add(imgNode) render.layer.add(imgGroup) // Load animated GIF const gifNode = await render.assetTool.loadGif('./assets/animation.gif') const gifGroup = new Konva.Group({ id: 'gif-1', name: 'asset', x: 500, y: 100, draggable: true }) gifGroup.add(gifNode) render.layer.add(gifGroup) // Load complex JSON composition const jsonGroup = await render.assetTool.loadJson('./assets/composition.json') jsonGroup.setAttrs({ x: 700, y: 100, draggable: true }) render.layer.add(jsonGroup) // Add connection points to assets jsonGroup.setAttr('points', [ { x: 0, y: 50, direction: 'left', id: 'p1', groupId: jsonGroup.id(), visible: false, pairs: [] }, { x: 100, y: 50, direction: 'right', id: 'p2', groupId: jsonGroup.id(), visible: false, pairs: [] } ]) // Update history after adding assets render.updateHistory() render.redraw() ``` -------------------------------- ### Manage Links and Connections with Konva Designer Source: https://context7.com/xachary/konva-designer-sample/llms.txt This snippet illustrates how to manage connections between nodes using Konva Designer. It covers defining connection points on nodes, showing/hiding these points, retrieving and updating link settings, and removing connections. Dependencies include Konva and the Render/types module. It also manages link visual styles like stroke, width, and arrow types. ```typescript import * as Types from './Render/types' // Define connection points on nodes const node1 = render.layer.findOne('#icon-1') as Konva.Group const node2 = render.layer.findOne('#photo-1') as Konva.Group // Add connection points to node1 node1.setAttr('points', [ { x: 100, y: 50, direction: 'right', id: 'point-1-right', groupId: node1.id(), visible: false, pairs: [{ id: 'pair-1', from: { groupId: node1.id(), pointId: 'point-1-right' }, to: { groupId: node2.id(), pointId: 'point-2-left' }, linkType: Types.LinkType.auto, style: { stroke: 'rgb(255,0,0)', strokeWidth: 2, arrowStart: false, arrowEnd: true, tension: 0.5 } }] } ]) // Add connection points to node2 node2.setAttr('points', [ { x: 0, y: 50, direction: 'left', id: 'point-2-left', groupId: node2.id(), visible: false, pairs: [] } ]) // Show connection points on hover render.linkTool.pointsVisible(true, node1) // Hide connection points render.linkTool.pointsVisible(false) // Get link settings const linkLine = render.layerCover.findOne('.link-line') as Konva.Line const linkSettings = render.getLinkSettings(linkLine) console.log('Link stroke:', linkSettings.stroke) // Update link settings await render.setLinkSettings(linkLine, { stroke: 'rgb(0,255,0)', strokeWidth: 3, arrowStart: true, arrowEnd: true, tension: 0.8 }, true) // Remove a connection render.linkTool.remove(linkLine) render.redraw(['LinkDraw', 'PreviewDraw']) ``` -------------------------------- ### Konva Designer: Text Management Source: https://context7.com/xachary/konva-designer-sample/llms.txt Shows how to add, edit, and style text elements on the Konva canvas. This includes enabling/disabling text mode, setting text content, font size, and color, and listening for changes in texting mode. Requires importing `Types` and assumes `render` is initialized. ```typescript import * as Types from './Render/types' // Enable text mode render.changeTexting(true) // Add text at specific position const textGroup = render.importExportTool.addTextAsset( { x: 100, y: 300 }, { text: 'Hello World', fontSize: 24, textFill: 'rgb(0,0,0)', stroke: '', strokeWidth: 0, fill: 'transparent', x: 100, y: 300, rotation: 0 } ) // Update text content and styling const textSettings = render.getAssetSettings(textGroup) await render.setAssetSettings(textGroup, { ...textSettings, text: 'Updated Text Content', fontSize: 32, textFill: 'rgb(255,0,0)' }, true) // Exit text mode render.changeTexting(false) // Listen to texting mode changes render.on('texting-change', (isTexting) => { console.log('Text mode:', isTexting ? 'ON' : 'OFF') }) render.updateHistory() render.redraw() ``` -------------------------------- ### Draw Basic Shapes with Konva Designer Source: https://context7.com/xachary/konva-designer-sample/llms.txt This snippet demonstrates how to draw various graph types including lines, rectangles, circles, and bezier curves using Konva Designer. It covers enabling drawing modes, programmatically creating graph elements, adding them to the layer, and updating the canvas. It requires Konva and the Render/types module. ```typescript import * as Types from './Render/types' // Enable line drawing mode render.changeGraphType(Types.GraphType.Line) // The user can now click on the canvas to draw lines // To programmatically create a graph: const lineGroup = new Konva.Group({ id: 'line-1', name: 'asset', assetType: Types.AssetType.Graph, graphType: Types.GraphType.Line, draggable: true, x: 100, y: 100 }) const line = new Konva.Arrow({ name: 'graph', points: [0, 0, 100, 100], stroke: 'rgb(0,0,0)', strokeWidth: 2, fill: 'rgb(0,0,0)', pointerAtBeginning: false, pointerAtEnding: true }) lineGroup.add(line) render.layer.add(lineGroup) // Draw rectangle render.changeGraphType(Types.GraphType.Rect) const rectGroup = new Konva.Group({ id: 'rect-1', name: 'asset', assetType: Types.AssetType.Graph, graphType: Types.GraphType.Rect, draggable: true, x: 200, y: 200 }) const rect = new Konva.Rect({ name: 'graph', width: 100, height: 80, stroke: 'rgb(0,0,0)', strokeWidth: 2, fill: 'transparent' }) rectGroup.add(rect) render.layer.add(rectGroup) // Draw circle render.changeGraphType(Types.GraphType.Circle) // Draw bezier curve render.changeGraphType(Types.GraphType.Bezier) // Exit drawing mode render.changeGraphType(undefined) render.updateHistory() render.redraw() ``` -------------------------------- ### Select and Manipulate Nodes with Konva Designer Source: https://context7.com/xachary/konva-designer-sample/llms.txt This snippet shows how to select specific or all nodes, move them programmatically, clear the selection, and manage asset settings like position, rotation, and stroke. It also includes listening for position change events. Dependencies include the Konva Designer render instance. ```typescript // Select specific nodes const node1 = render.layer.findOne('#icon-1') const node2 = render.layer.findOne('#photo-1') render.selectionTool.select([node1, node2]) // Select all nodes render.selectionTool.selectAll() // Move selected nodes programmatically render.selectionTool.selectingNodesMove({ x: 50, y: 0 }) // Clear selection render.selectionTool.selectingClear() // Get asset settings const settings = render.getAssetSettings(node1) console.log('Position:', settings.x, settings.y) console.log('Rotation:', settings.rotation) console.log('Stroke:', settings.stroke) // Update asset settings await render.setAssetSettings(node1, { ...settings, x: 200, y: 150, rotation: 45, stroke: 'rgb(255,0,0)', strokeWidth: 3, fill: 'rgb(0,0,255)' }, true) // true = update history // Listen to position changes render.on('asset-position-change', (nodes) => { nodes.forEach(node => { const pos = node.position() console.log(`${node.id()} moved to (${pos.x}, ${pos.y})`) }) }) ``` -------------------------------- ### Import and Export Canvas State and Assets Source: https://context7.com/xachary/konva-designer-sample/llms.txt Provides functionality to save and load the entire canvas state as JSON, export the canvas as PNG or SVG, and export selected assets as images or JSON. It utilizes local storage for state persistence and DOM manipulation for file downloads. Dependencies include the Konva Designer's importExportTool. ```typescript const jsonState = render.importExportTool.save() localStorage.setItem('canvas-state', jsonState) console.log('Saved canvas state') const savedState = localStorage.getItem('canvas-state') if (savedState) { await render.importExportTool.restore(savedState, false) console.log('Loaded canvas state') } const pngDataUrl = render.importExportTool.getImage(2, 'rgb(255,255,255)') const link = document.createElement('a') link.download = 'design.png' link.href = pngDataUrl link.click() const assetImageUrl = render.importExportTool.getAssetImage(2, 'transparent') const svgContent = await render.importExportTool.getSvg() const svgBlob = new Blob([svgContent], { type: 'image/svg+xml' }) const svgUrl = URL.createObjectURL(svgBlob) const svgLink = document.createElement('a') svgLink.download = 'design.svg' svgLink.href = svgUrl svgLink.click() const assetJson = render.importExportTool.getAsset() const assetBlob = new Blob([assetJson], { type: 'application/json' }) const assetUrl = URL.createObjectURL(assetBlob) const viewCopy = render.importExportTool.getView(false) const viewJson = viewCopy.toJSON() viewCopy.destroy() ``` -------------------------------- ### Coordinate Conversion (TypeScript) Source: https://context7.com/xachary/konva-designer-sample/llms.txt Convert pixel values between the board's coordinate system and the stage's coordinate system. 'toStageValue' converts board pixels to stage units, while 'toBoardValue' converts stage units back to board pixels. Essential for accurate positioning and scaling. ```typescript // Convert coordinates const stageValue = render.toStageValue(100) // Board pixels to stage units const boardValue = render.toBoardValue(100) // Stage units to board pixels ``` -------------------------------- ### Subscribe to Canvas Events Source: https://context7.com/xachary/konva-designer-sample/llms.txt Allows developers to subscribe to a variety of canvas events to create reactive user interfaces. Events cover selection changes (nodes and links), asset transformations (position and rotation), graph type changes, debug mode toggles, loading states, and scale adjustments. Event listeners can be added using `render.on()` and removed using `render.off()`. ```typescript render.on('selection-change', (nodes) => { if (nodes.length === 0) { console.log('Nothing selected') } else if (nodes.length === 1) { console.log('Single selection:', nodes[0].id()) } else { console.log('Multi selection:', nodes.length, 'nodes') } }) render.on('link-selection-change', (link) => { if (link) { console.log('Link selected:', link.attrs.pairId) } else { console.log('Link deselected') } }) render.on('asset-position-change', (nodes) => { nodes.forEach(node => { const pos = node.position() console.log(`${node.id()} at (${pos.x.toFixed(1)}, ${pos.y.toFixed(1)})`) }) }) render.on('asset-rotation-change', (nodes) => { nodes.forEach(node => { console.log(`${node.id()} rotated to ${node.rotation().toFixed(1)}°`) }) }) render.on('graph-type-change', (graphType) => { console.log('Graph mode:', graphType ?? 'none') }) render.on('debug-change', (debug) => { console.log('Debug mode:', debug ? 'ON' : 'OFF') }) render.on('loading', (isLoading) => { document.getElementById('loader')!.style.display = isLoading ? 'block' : 'none' }) render.on('scale-change', (scale) => { console.log('Zoom level:', (scale * 100).toFixed(0) + '%') }) const handler = (nodes) => console.log('Selection:', nodes.length) render.on('selection-change', handler) render.off('selection-change', handler) ``` -------------------------------- ### Manage Undo/Redo History Source: https://context7.com/xachary/konva-designer-sample/llms.txt Enables management of the undo and redo functionality for canvas operations. History is automatically tracked for common actions, but manual updates are also supported. Event listeners can be attached to monitor history changes and update UI elements accordingly. Key methods include `updateHistory`, `prevHistory`, and `nextHistory`. ```typescript render.updateHistory() render.prevHistory() render.nextHistory() render.on('history-change', ({ records, index }) => { const canUndo = index > 0 const canRedo = index < records.length - 1 console.log(`Can undo: ${canUndo}, Can redo: ${canRedo}`) console.log(`History size: ${records.length} records`) document.getElementById('undo-btn')!.disabled = !canUndo document.getElementById('redo-btn')!.disabled = !canRedo }) console.log('Current index:', render.historyIndex) console.log('Total records:', render.history.length) ``` -------------------------------- ### Selective and Full Redraw (TypeScript) Source: https://context7.com/xachary/konva-designer-sample/llms.txt Perform a selective redraw of specific canvas components for performance optimization, or execute a full redraw of the entire canvas. Selective redraws accept an array of component names to update. ```typescript // Selective redraw for performance render.redraw(['LinkDraw', 'RulerDraw', 'PreviewDraw']) // Full redraw render.redraw() ``` -------------------------------- ### Debug and Draggable Control (TypeScript) Source: https://context7.com/xachary/konva-designer-sample/llms.txt Enable or disable the visual debug mode, which displays helper elements for easier debugging. Also controls the draggable state of all assets on the canvas, allowing or preventing user interaction for moving nodes. ```typescript // Enable/disable debug mode render.changeDebug(true) // Shows all visual helpers // Control node dragging render.changeDraggable(true) // Enable dragging for all assets render.changeDraggable(false) // Disable dragging ``` -------------------------------- ### Ignore Node Checks (TypeScript) Source: https://context7.com/xachary/konva-designer-sample/llms.txt Determine if a node should be ignored by various helper functions, such as selection, drawing, or linking. 'ignore()' checks if the node is generally ignored, while specific functions like 'ignoreSelect()', 'ignoreDraw()', and 'ignoreLink()' provide more granular checks. ```typescript // Ignore checks for filtering const node = render.layer.findOne('#some-node') const shouldIgnore = render.ignore(node) const isSelectHelper = render.ignoreSelect(node) const isDrawHelper = render.ignoreDraw(node) const isLinkHelper = render.ignoreLink(node) ``` -------------------------------- ### Remove Nodes from Canvas (TypeScript) Source: https://context7.com/xachary/konva-designer-sample/llms.txt Remove specific nodes from the canvas by providing an array of node references. Nodes can be found using methods like 'layer.findOne()'. This is useful for deleting elements from the design. ```typescript // Remove nodes const nodesToRemove = [ render.layer.findOne('#icon-1'), render.layer.findOne('#photo-1') ] render.remove(nodesToRemove) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.