Rough.js

repository·master·Indexed 12 days ago

https://github.com/rough-stuff/rough

A lightweight graphics library for creating hand-drawn, sketchy style drawings on HTML Canvas or SVG. Version 4.6.6 provides tools like RoughCanvas, RoughSVG, and RoughGenerator to render shapes including lines, rectangles, ellipses, and polygons with customizable fill styles such as hachure, zigzag, cross-hatch, and dots.

Tokens
7.3K
Snippets
36
Records
37
Agent score
97%

What's inside Rough.js

  1. Install Rough.js

    master

    You can install Rough.js via npm or use it directly in the browser via unpkg.

    npm installation:

    npm install --save roughjs

    Browser usage (unpkg): Use https://unpkg.com/roughjs@latest/bundled/rough.js.

    Bundled formats available in the npm package:

    • CommonJS: roughjs/bundled/rough.cjs.js
    • ESM: roughjs/bundled/rough.esm.js
    • Browser IIFE: roughjs/bundled/rough.js
  2. Initialize Rough.js for Canvas or SVG

    master

    Rough.js supports both HTML5 Canvas and SVG. You initialize a drawing instance by calling rough.canvas() or rough.svg().

    For Canvas: Pass the canvas element to rough.canvas(). Drawing commands will be executed directly on the canvas.

    For SVG: Pass the SVG element to rough.svg(). Drawing commands will return SVG nodes that you must manually append to the SVG element.

    // Canvas usage
    const rc = rough.canvas(document.getElementById('canvas'));
    rc.rectangle(10, 10, 200, 200); // x, y, width, height
    
    // SVG usage
    const rc = rough.svg(svg);
    let node = rc.rectangle(10, 10, 200, 200); // x, y, width, height
    svg.appendChild(node);
  3. Initialize RoughGenerator

    master

    To use Rough.js, instantiate the RoughGenerator class. You can provide an optional Config object in the constructor to set global default options for all shapes generated by that instance.

    import { RoughGenerator } from './generator.js';
    
    // Use default settings
    const generator = new RoughGenerator();
    
    // Use custom global settings
    const generator = new RoughGenerator({
      options: {
        stroke: '#ff0000',
        roughness: 2
      }
    });
    import { RoughGenerator } from './generator.js';
    
    const generator = new RoughGenerator({
      options: {
        stroke: '#ff0000',
        roughness: 2
      }
    });
  4. Initialize RoughCanvas to draw on a canvas element

    master

    To use Rough.js for drawing sketchy shapes directly onto an HTML5 Canvas, instantiate the RoughCanvas class. You must provide an existing HTMLCanvasElement and an optional Config object. The class manages its own RoughGenerator and the 2D rendering context.

    import { RoughCanvas } from 'roughjs';
    
    const canvas = document.getElementById('my-canvas') as HTMLCanvasElement;
    const rc = new RoughCanvas(canvas);
  5. Draw basic shapes: Lines, Circles, and Ellipses

    master

    Use the following methods on your Rough instance (rc) to draw basic primitives:

    • rc.circle(centerX, centerY, diameter)
    • rc.ellipse(centerX, centerY, width, height)
    • rc.line(x1, y1, x2, y2)
    rc.circle(80, 120, 50); // centerX, centerY, diameter
    rc.ellipse(300, 100, 150, 80); // centerX, centerY, width, height
    rc.line(80, 120, 300, 100); // x1, y1, x2, y2
  6. Draw SVG paths

    master

    You can draw complex shapes using standard SVG path data strings via the rc.path() method. You can also provide a fill option to color the path.

    rc.path('M80 80 A 45 45, 0, 0, 0, 125 125 L 125 80 Z', { fill: 'green' });
  7. Adjust sketching style and roughness

    master

    You can control the 'hand-drawn' look of your shapes using the following options in the options object:

    • roughness: Controls how 'sketchy' the lines are (higher values = more irregular).
    • bowing: Controls the curvature of the lines.
    • stroke: The color of the outline.
    • strokeWidth: The thickness of the outline.
    // High roughness
    rc.rectangle(15, 15, 80, 80, { roughness: 0.5, fill: 'red' });
    
    // Very high roughness
    rc.rectangle(120, 15, 80, 80, { roughness: 2.8, fill: 'blue' });
    
    // Using bowing and stroke width
    rc.rectangle(220, 15, 80, 80, { bowing: 6, stroke: 'green', strokeWidth: 3 });
  8. Configure filling and hachure styles

    master

    Rough.js allows you to fill shapes with various hand-drawn styles. You can pass an options object as the last argument to shape methods.

    Available fillStyle values:

    • hachure (default)
    • solid
    • zigzag
    • cross-hatch
    • dots
    • dashed
    • zigzag-line

    Common Fill Options:

    • fill: The color of the fill (e.g., 'red', 'rgb(10,150,10)', 'rgba(255,0,200,0.2)').
    • fillStyle: The style of the fill (see list above).
    • fillWeight: Thickness of the hachure lines.
    • hachureAngle: The angle of the hachure lines.
    • hachureGap: The spacing between hachure lines.
    // Example: Solid fill
    rc.rectangle(120, 105, 80, 80, { fill: 'rgba(255,0,200,0.2)', fillStyle: 'solid' });
    
    // Example: Custom hachure
    rc.rectangle(220, 15, 80, 80, {
      fill: 'red',
      hachureAngle: 60,
      hachureGap: 8
    });
    
    // Example: Thicker hachure lines
    rc.circle(50, 150, 80, {
      fill: 'rgb(10,150,10)',
      fillWeight: 3
    });
  9. Generate a random seed

    master

    Use the static method RoughGenerator.newSeed() to generate a new numeric seed. This is useful for ensuring different but reproducible randomness if you want to manually manage seeds.

    const seed = RoughGenerator.newSeed();
    const generator = new RoughGenerator({ options: { seed } });
  10. Generate random offsets

    master

    Use randOffset or randOffsetWithRange to get random values influenced by the current roughness and seed in the ResolvedOptions.

    import { randOffset, randOffsetWithRange } from './renderer';
    
    // Returns an offset based on options
    const offset = randOffset(10, options);
    
    // Returns an offset within a specific range
    const rangeOffset = randOffsetWithRange(5, 15, options);
  11. Use the draw() method to render Drawable objects

    master

    If you already have a Drawable object (for example, generated via a RoughGenerator), you can render it to the RoughCanvas using the draw(drawable: Drawable) method. This method iterates through the drawing sets and applies the specified options like stroke, fill, strokeWidth, and dash patterns.

    const drawable = rc.generator.rectangle(0, 0, 100, 100);
    rc.draw(drawable);
  12. Draw a polygon

    master

    Use polygon to draw a closed shape defined by an array of Point objects. This is a convenience wrapper around linearPath with close set to true.

    import { polygon, type Point } from './renderer';
    const points: Point[] = [[10, 10], [50, 10], [50, 50], [10, 50]];
    const ops = polygon(points, options);