potpack 2.1.0

repository·main·Indexed 43 days ago

https://github.com/mapbox/potpack

A tiny JavaScript library for packing 2D rectangles into a near-square container, designed for maximal space utilization in CSS sprites and WebGL textures.

Tokens
794
Snippets
6
Records
6
Agent score
6%

What's inside potpack

  1. Use potpack in a browser via ES modules

    main

    Since potpack is an ES module, you can import it directly in modern browsers using a <script type="module"> tag. Note that it does not support Internet Explorer.

    <script type="module">
    import potpack from 'https://cdn.skypack.dev/potpack';
    ...
    </script>
  2. Pack 2D rectangles with potpack()

    main

    Use potpack(boxes) to pack an array of rectangles into a near-square container. This is ideal for generating CSS sprites or WebGL textures.

    Input Format: Pass an array of objects where each object defines the dimensions of a box using w (width) and h (height).

    Side Effects:

    • Mutation: The input boxes array is mutated. It is sorted by height, and each box object is augmented with x and y coordinates representing its position in the container.

    Return Value: Returns an object containing:

    • w: The width of the resulting container.
    • h: The height of the resulting container.
    • fill: The space utilization value (a float between 0 and 1, where higher is better).
    import potpack from 'potpack';
    
    const boxes = [
        {w: 300, h: 50},
        {w: 100, h: 200},
        // ... more boxes
    ];
    
    const {w, h, fill} = potpack(boxes);
    
    // boxes[0] is now augmented with coordinates:
    // {w: 300, h: 50, x: 100, y: 0}
  3. PotpackBox type definition

    main

    A PotpackBox represents a rectangle used for packing. The input objects must provide w and h, and the function will add x and y coordinates to them.

    /**
     * @typedef {Object} PotpackBox
     * @property {number} w Box width.
     * @property {number} h Box height.
     * @property {number} [x] X coordinate in the resulting container.
     * @property {number} [y] Y coordinate in the resulting container.
     */
  4. PotpackStats type definition

    main

    A PotpackStats object contains the metadata about the resulting packed container.

    /**
     * @typedef {Object} PotpackStats
     * @property {number} w Width of the resulting container.
     * @property {number} h Height of the resulting container.
     * @property {number} fill The space utilization value (0 to 1). Higher is better.
     */