modern-screenshot

repository·main·Indexed 24 days ago

https://github.com/qq15725/modern-screenshot

A library for quickly generating images (PNG, JPEG, WebP, SVG) or other formats (Canvas, Blob, Pixel) from DOM nodes using HTML5 canvas and SVG. Version 4.7.0 provides functions such as domToBlob, domToCanvas, domToDataUrl, domToImage, and domToForeignObjectSvg to convert DOM elements into various output types, along with comprehensive Options for configuring rendering, asset fetching, and lifecycle hooks.

Tokens
1.6K
Snippets
0
Records
10
Agent score
84%

What's inside modern-screenshot

  1. Convert DOM nodes to Blobs with domToBlob

    main
    The domToBlob function converts a DOM node into a Blob object. It supports two usage patterns: passing a DOM node directly with an optional Options object, or passing a pre-existing Context object. If a dpi is provided in the options, the function will attempt to adjust the DPI for image/png and image/jpeg types.
  2. Convert DOM nodes to Data URLs with domToDataUrl

    main

    The domToDataUrl function converts a DOM node into a Data URL string (e.g., data:image/png;base64,...). It supports both direct node input with an options object or passing a pre-constructed Context.

    When using image/png or image/jpeg types, the function can also handle DPI adjustments if a dpi is provided in the options, ensuring the resulting image reflects the requested resolution.

    Overloads

    • domToDataUrl<T extends Node>(node: T, options?: Options): Promise<string>
    • domToDataUrl<T extends Node>(context: Context<T>): Promise<string>
  3. Manage screenshot context with createContext and destroyContext

    main
    To manage the lifecycle of the screenshotting process, use createContext to initialize a new context and destroyContext to clean up resources when finished. This is useful for managing the singleton context or web worker environments used by the library.
  4. Convert DOM nodes to SVG using domToForeignObjectSvg

    main

    The domToForeignObjectSvg function converts a DOM node (or a Context) into an SVGElement by wrapping the node inside a <foreignObject> element within an SVG. This is useful for embedding HTML content into an SVG structure, often used as an intermediate step for high-fidelity screenshots.

    Key behaviors:

    • It automatically handles cloning the node and embedding external resources (like images or web fonts).
    • It supports lifecycle hooks via the Options object to intercept the cloning and embedding processes.
    • It can automatically clean up the context if autoDestruct is enabled in the options.

    Arguments:

    • node: The DOM Node to be converted.
    • options (optional): An Options object to configure the conversion process.
  5. Convert DOM nodes to HTMLCanvasElement with domToCanvas

    main

    The domToCanvas function is the primary entry point for converting a DOM node into an HTMLCanvasElement. It supports two calling patterns:

    1. Direct Node and Options: Pass the target Node and an optional Options object.
    2. Context-based: Pass an existing Context object.

    The function internally converts the DOM node into a foreignObject SVG, generates a Data URL, and then renders that into a canvas. If context.autoDestruct is false, the function manages the lifecycle of style and defs elements within the context.

  6. Use utility functions loadMedia and waitUntilLoad

    main

    The library exports utility functions to handle media loading during the screenshot process:

    • loadMedia: Explicitly loads media resources.
    • waitUntilLoad: Ensures that resources are fully loaded before proceeding with operations.
  7. Convert DOM to various image formats and types

    main
    The modern-screenshot library provides several functions to convert DOM elements into different formats. Use these functions depending on your required output type (e.g., Blob, Canvas, Data URL, or specific image formats like PNG, JPEG, WebP, or SVG).
  8. Convert a DOM node to an HTMLImageElement with domToImage

    main
    The domToImage function converts a DOM node into an HTMLImageElement. It supports two primary invocation patterns: passing a DOM node directly with an optional Options object, or passing a Context object. The function handles the conversion process (either via SVG or Data URL depending on the type) and returns an image element with dimensions scaled according to the provided options.
  9. Configure screenshot generation with Options

    main

    The Options interface allows you to customize the rendering, image quality, asset fetching, and lifecycle hooks of the screenshot process.

    Core Rendering Options

    • width / height: Dimensions in pixels applied to the node before rendering.
    • scale: The pixel ratio (DPI = 96 * scale). Default is 1.
    • type: Image format (e.g., image/png). Default is image/png.
    • quality: A number between 0 and 1 for JPEG quality (e.g., 0.92 for 92%).
    • backgroundColor: A valid CSS color string or null.
    • style: A Partial<CSSStyleDeclaration> to apply to the node before rendering.
    • maximumCanvasSize: Limits the maximum canvas size in pixels.
    • timeout: Timeout for media loading and remote asset fetching in milliseconds. Default is 30000.
    • debug: Boolean to enable execution time logging.

    Asset Fetching and Fonts

    • fetchFn: A custom implementation to retrieve image data (useful for bypassing CORS in environments like Capacitor/Cordova). If it returns a string, it bypasses Options.fetch settings. If it returns false, it falls back to standard fetch.
    • fetch: Configuration for resource fetching:
      • requestInit: RequestInit options for window.fetch.
      • bypassingCache: If true, appends current time as a query string to URLs to bust cache.
      • placeholderImage: A data URL or a function returning a data URL to use when an image fetch fails.
    • font: Configuration for font embedding:
      • minify: Function to minify font ArrayBuffers.
      • preferredFormat: Preferred format (e.g., 'woff2', 'woff', 'truetype').
      • cssText: A CSS string to specify exactly which font embeds are present.

    Feature Toggles

    • features: A boolean or an object to enable/disable specific behaviors:
      • copyScrollbar: Copy scrollbar CSS styles (default: true).
      • removeAbnormalAttributes: Normalize XML by removing abnormal attributes (default: true).
      • removeControlCharacter: Normalize XML by removing control characters (default: true).
      • fixSvgXmlDecode: Fix SVG+XML decoding for Safari/Firefox (default: true).
      • restoreScrollPosition: Render scrolled children with their scrolled content (default: false).

    Lifecycle Hooks

    • filter: A function (el: Node) => boolean. If it returns false, the node and its children are excluded from the output.
    • progress: Callback (current: number, total: number) => void for asset embedding progress.
    • onCloneEachNode: Triggered after each individual node is cloned.
    • onCloneNode: Triggered after a node is cloned.
    • onEmbedNode: Triggered after a node is embedded.
    • onCreateForeignObjectSvg: Triggered after a ForeignObjectSvg is created.
    • onCloneEachNode: Triggered after each node is cloned.