zrender Documentation

repository·master·Indexed 27 days ago

https://github.com/ecomfe/zrender

A lightweight 2D graphics library serving as the underlying drawing engine for Apache ECharts. Version 6.1.0 provides capabilities for web-based visualizations, including a state system for Displayable objects, incremental rendering for large datasets, and utilities for SVG virtual node creation and serialization.

Tokens
2K
Snippets
1
Records
17
Agent score
92%

What's inside zrender

  1. Import the official ZRender entry point

    master

    Only zrender.js is officially exported for user consumption. While other entries in the package.json exports field are accessible for backward compatibility, they are considered internal and their usage is not recommended.

    When importing, ensure you use the official entry point to avoid issues with internal file access.

  2. Implement incremental rendering for large datasets

    master

    For elements that need to render incrementally (like a very large path), use the incremental property and the beforeBrush hook. Setting notClear: true can prevent the incremental layer from clearing even when a redraw is triggered, allowing you to manage the drawing index manually.

    Typical Pattern:

    1. Set incremental to a non-zero value.
    2. In beforeBrush(param), check param.contentRetained. If false, reset your internal drawing index.
    3. In your drawing logic, use the index to draw only a subset of data and set notClear = true to retain the existing canvas content.
    class LargePath extends Path {
        reset() {
            this._idx = 0;
            this.notClear = false;
        }
        beforeBrush(param: BeforeBrushParam) {
            if (!param.contentRetained) { this.reset(); }
        }
        buildPath() {
            for (this._idx; this._idx < this.shape.points.length; this._idx++) {
                // draw logic here
            }
            this.notClear = true;
        }
    }
  3. Manage element states

    master

    Displayable objects support a state system to manage different visual configurations (e.g., 'hover' or 'pressed').

    • getState(stateName: string): Retrieves the state by name.
    • ensureState(stateName: string): Ensures the state exists and returns it.
    • states: A dictionary containing all defined states.
    • stateProxy(stateName: string): A proxy function to access states.
  4. Animate style properties

    master

    You can animate changes to an element's style using the animate() or animateStyle() methods. animateStyle(loop?: boolean) is a convenient alias for animate('style', loop).

    By default, the following common style properties are animatable:

    • shadowBlur
    • shadowOffsetX
    • shadowOffsetY
    • shadowColor
    • opacity
  5. Generate CSS and Keyframe Strings with getCssString

    master

    Use getCssString to generate a CSS string wrapped in a <![CDATA[ block from provided selector and animation nodes. This is typically used for embedding styles within an SVG.

    Parameters:

    • selectorNodes: Record<string, CSSSelectorVNode> mapping class names to attribute sets.
    • animationNodes: Record<string, CSSAnimationVNode> mapping animation names to keyframe percentages and their respective styles.
    • opts: { newline?: boolean }
  6. Create SVG Virtual Nodes with createVNode and createSVGVNode

    master

    ZRender provides utilities to create Virtual DOM nodes (SVGVNode) for SVG rendering.

    • createVNode(tag, key, attrs, children, text): Creates a generic virtual node.
    • createSVGVNode(width, height, children, useViewBox): A specialized helper to create the root <svg> element with standard attributes like xmlns and version already configured.

    SVGVNode structure:

    • tag: string
    • attrs: Record<string, string | number | undefined | boolean>
    • children: SVGVNode[] (optional)
    • text: string (optional)
    • key: string
  7. Configure styles for Displayable objects

    master

    Displayable objects use a style property to define visual attributes. You can set styles using setStyle() or by passing a style object to the constructor. Common style properties include shadowBlur, shadowOffsetX, shadowOffsetY, shadowColor, opacity, and blend (the CSS globalCompositeOperation).

    To ensure a style object has all necessary default values, use createStyle().

  8. Initialize a BrushScope with createBrushScope

    master

    A BrushScope is a container used during the SVG generation process to manage caches (shadows, gradients, patterns, clipPaths), definitions (defs), and CSS nodes/animations. Use createBrushScope(zrId) to initialize a new scope.

    Key properties in BrushScope:

    • defs: Record<string, SVGVNode>
    • cssNodes: Record<string, CSSSelectorVNode>
    • cssAnims: Record<string, Record<string, Record<string, string>>>
    • shadowCache, gradientCache, patternCache, clipPathCache: Caches for reusable SVG definitions.
  9. Convert SVGVNode to SVG String with vNodeToString

    master

    The vNodeToString function converts an SVGVNode tree into a raw SVG string. This is useful for serialization or SSR (Server Side Rendering).

    Options:

    • newline: boolean (default false). If true, inserts newlines between elements.
  10. Configure text alignment and vertical alignment

    master

    When working with text elements, you can specify alignment using the following types:

    • TextVerticalAlign: 'top' | 'middle' | 'bottom'
    • TextAlign: 'left' | 'center' | 'right'
    • FontWeight: 'normal' | 'bold' | 'bolder' | 'lighter' | number
    • FontStyle: 'normal' | 'italic' | 'oblique'
  11. Reference DisplayableProps

    master

    The following properties are available on Displayable objects to control rendering and interaction:

    PropertyTypeDescription
    styleDictionary<any>Visual attributes (opacity, shadow, etc.)
    zlevelnumberDetermines which layer canvas the object is drawn in
    znumberZ-order within a layer
    z2numberSecondary Z-order
    invisiblebooleanIf true, the object is not drawn but can still trigger mouse events
    cullingbooleanIf true, enables culling (skipping drawing if outside view)
    cursorstringMouse cursor style when hovered
    rectHoverbooleanIf true, the hover area is the bounding rectangle
    incrementalIncrementalIdCompatConfiguration for incremental rendering
    ignoreCoarsePointerbooleanPrevents increasing to target size
    batchbooleanBatching flag
    progressivebooleanProgressive rendering flag
    notClearbooleanUsed for incremental elements to retain layer content