svg2roughjs

repository·master·Indexed 42 days ago

https://github.com/fskpf/svg2roughjs

A utility that leverages Rough.js to convert standard SVG files into hand-drawn, sketchy visualizations. It supports output to HTML containers, SVG elements, or Canvas elements and includes a Node.js CLI for command-line conversion using Puppeteer. Version 3.2.3.

Tokens
4.7K
Snippets
15
Records
20
Agent score
53%

What's inside svg2roughjs

  1. Install and use the svg2roughjs CLI

    master

    The svg2roughjs-nodejs CLI allows you to create hand-drawn sketches of SVG files from the command line using Node.js and Puppeteer.

    To use it, navigate to the /nodejs-cli/ directory, install dependencies, and run the script pointing to your source SVG file.

    # Navigate to the CLI directory
    cd nodejs-cli
    
    # Install dependencies
    npm install
    
    # Run the conversion
    node src/svg2roughjs ../test/complex/bpmn-diagram/test.svg -o ./test.svg
  2. Use svg2roughjs via UMD Bundle (Script Tag)

    master

    Load the UMD bundle directly from unpkg via a script tag. The library will be available under the svg2roughjs global object.

    <!-- script loading -->
    <script src="https://unpkg.com/svg2roughjs/dist/svg2roughjs.umd.min.js"></script>
    <script>
      const svgConverter = new svg2roughjs.Svg2Roughjs('#output-div')
      svgConverter.svg = document.getElementById('input-svg')
      svgConverter.sketch()
    </script>
  3. Use svg2roughjs as an ES Module

    master

    Import Svg2Roughjs from the package, instantiate it with a target container selector or element, assign the source SVGSVGElement to the svg property, and call sketch() to perform the conversion.

    import { Svg2Roughjs } from 'svg2roughjs'
    
    const svg2roughjs = new Svg2Roughjs('#output-div')
    svg2roughjs.svg = document.getElementById('input-svg')
    svg2roughjs.sketch()
  4. Use svg2roughjs with RequireJS

    master

    Load the UMD bundle using RequireJS to access the Svg2Roughjs class.

    <!-- requirejs -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
    <script>
      window.requirejs(['https://unpkg.com/svg2roughjs/dist/svg2roughjs.umd.min.js'], svg2roughjs => {
        const svgConverter = new svg2roughjs.Svg2Roughjs('#output-div')
        svgConverter.svg = document.getElementById('input-svg')
        svgConverter.sketch()
      });
    </script>
  5. Configure web-test-runner

    master

    The project uses @web/test-runner for testing. Configuration is defined in a web-test-runner.config.mjs file by exporting a TestRunnerConfig object.

    Key configuration options include:

    • files: An array of paths to the test files to be executed.
    • plugins: An array of plugins to extend the runner's functionality (e.g., using rollupBundlePlugin to handle dependency bundling).
    • reporters: An array of reporter objects to control how test results are displayed (e.g., defaultReporter and summaryReporter).
    • coverage: A boolean to enable or disable code coverage analysis.
    • manual: A boolean that, when true, allows running tests manually in a browser for debugging.
    • nodeResolve: Configuration for resolving bare module imports, including exportConditions.
    • rootDir: The root directory for the test runner.
    • filterBrowserLogs: A function used to filter out specific logs from the browser output.
    • concurrency: The number of test files to run concurrently per browser.
    • concurrentBrowsers: (Commented out in source) The number of browsers to run concurrently.
    export default /** @type {import("@web/test-runner").TestRunnerConfig} */ ({
      files: ['test/runner/spec.test.js', 'test/runner/complex.test.js'],
      plugins: [
        rollupBundlePlugin({
          rollupConfig: {
            input: 'out-tsc/index.js',
            plugins: [nodeResolve(), commonjs()]
          }
        })
      ],
      reporters: [
        defaultReporter({ reportTestResults: false, reportTestProgress: true }),
        summaryReporter()
      ],
      coverage: false,
      manual: false,
      nodeResolve: {
        exportConditions: ['browser', 'development']
      },
      rootDir: './',
      concurrency: 1
    })
  6. Svg2Roughjs Class API Reference

    master

    The Svg2Roughjs class is the primary interface for converting SVGs to hand-drawn sketches using Rough.js.

    Constructor

    constructor(target, outputType?, roughConfig?)

    • target: A container HTMLDivElement (or selector) where the sketch will be created, or a direct SVGSVGElement or HTMLCanvasElement to be used as the output.
    • outputType (optional): Determines the output format. Defaults to OutputType.SVG if the target is an HTML container. If the target is an SVGSVGElement or HTMLCanvasElement, it defaults to the respective mode.
    • roughConfig (optional): A Rough.js options object to customize styles like fill, roughness, or bowing.
    // Example instantiation
    const converter = new Svg2Roughjs('#output-container', OutputType.CANVAS, { roughness: 2 });
  7. Svg2Roughjs Methods

    master

    sketch(sourceSvgChanged = false): Promise<SVGSVGElement | HTMLCanvasElement | null>

    Clears the configured target element and converts the current svg2roughjs.svg into a hand-drawn sketch.

    If sourceSvgChanged is set to true, the method re-evaluates the existing svg property as if it were newly set. This is useful for re-using the same instance and source element for multiple renders.

  8. Svg2Roughjs Properties

    master

    Configure the conversion behavior using the following properties on an Svg2Roughjs instance:

    PropertyDescriptionDefault
    svgThe SVGSVGElement to be converted.undefined
    outputTypeSwitch between CANVAS or SVG output.OutputType.SVG
    roughConfigRough.js options object (e.g. fill-style, roughness).{}
    fontFamilyFont for text elements. If null, uses the original font-family.'Comic Sans MS, cursive'
    backgroundColorBackground color for the sketch.'transparent'
    randomizeWhether to randomize Rough.js fillWeight, hachureAngle, and hachureGap.true
    seedNumerical seed for randomness.null
    sketchPatternsWhether to sketch pattern fills/strokes or just copy them.true
    pencilFilterApplies a pencil effect to the SVG rendering.false
  9. CLI Parameters for svg2roughjs

    master

    The CLI accepts the source SVG file as the first positional parameter. You can also provide several optional flags to control the output and the roughness style.

    Positional Argument:

    • [input-file]: The path to the SVG file you want to convert.

    Optional Flags:

    ParameterDescription
    -o, --outputOutput path for the resulting sketch. Defaults to './sketch.svg'.
    --roughConfig.ROUGHJS_PROPERTYPass specific properties to the underlying roughjs engine (e.g., --roughConfig.roughness 1.5).
    --fontFamilySets the font family for text elements.
    --backgroundColorSets the background color of the sketch.
    --randomizeEnables randomization of sketch elements.
    --seedSets a seed for reproducible randomization.
    --sketchPatternsConfigures sketch patterns.
    --pencilFilterConfigures the pencil filter effect.

    Note: For detailed property names available under --roughConfig, refer to the main svg2roughjs documentation.

    node src/svg2roughjs ../test/complex/bpmn-diagram/test.svg -o ./test.svg --roughConfig.roughness 1.5 --roughConfig.bowing 2 --backgroundColor white --fontFamily null
  10. Configure Rough.js rendering via roughConfig

    master

    The roughConfig property allows you to pass any valid Options object from Rough.js to the underlying renderer. This controls the specific hand-drawn styles of lines, fills, and hatches.

    Note: If you do not specify fixedDecimalPlaceDigits in your config, Svg2Roughjs will automatically set it to 3 to ensure precision during coordinate processing.

    instance.roughConfig = {
      strokeWidth: 2,
      stroke: '#000',
      roughness: 1.5,
      // fixedDecimalPlaceDigits is automatically set to 3 if omitted
    };