Raphaël JavaScript Vector Library

repository·master·Indexed 11 days ago

https://github.com/dmitrybaranovskiy/raphael

A cross-browser JavaScript vector graphics library (version 2.3.0) used to draw shapes and animations in the browser. It provides a Paper API for creating circles, rectangles, ellipses, paths, images, and text, along with tools for attribute manipulation, geometric transformations (rotate, scale, translate), Z-order management, and a built-in animation system.

Tokens
4.2K
Snippets
19
Records
20
Agent score
92%

What's inside Raphaël

  1. Build Raphaël from source

    master

    To build the library from the repository, you must have NPM and Yarn installed. Run the following commands in the root directory:

    1. Clone the repository.
    2. Install dependencies using Yarn.
    3. Run the build command.
    git clone https://github.com/DmitryBaranovskiy/raphael.git
    yarn install --frozen-lockfile
    yarn build-all
  2. Initialize a Raphael Paper

    master

    To use Raphaël, you first need to create a Paper instance. This instance acts as the canvas for all your vector graphics. You can specify a container element (like a div ID), its position (x, y), and its dimensions (width, height).

    If you provide a numeric value for dimensions, it is treated as pixels. If you provide a string, it is used as-is.

    Note: If the container is not found, an error will be thrown.

    // Assuming Raphael is loaded in the global scope
    var paper = Raphael('container-id', 512, 342);
    // Or with specific positioning
    var paper = Raphael('container-id', 0, 0, 512, 342);
  3. Manage groups of elements with Sets

    master

    A set is a collection of Raphaël elements that allows you to perform operations on all members simultaneously. You can create a set using paper.set() or by calling element.set() on an existing element.

    Common Set Operations:

    • set.attr(attr, value): Applies an attribute to all elements in the set.
    • set.animate(attributes, duration, ...): Animates all elements in the set.
    • set.forEach(callback): Iterates through the elements.
    • set.clone(): Returns a new set containing clones of the elements in the current set.
    • set.insertAfter(element) / set.insertBefore(element): Moves all elements in the set relative to a target element.
    • set.getBBox(): Returns the combined bounding box of all elements in the set.
    var mySet = paper.set();
    mySet.push(circle1, rect1, path1);
    
    // Apply attribute to all
    mySet.attr('fill', '#ff0000');
    
    // Animate all
    mySet.animate({ opacity: 0 }, 500);
  4. Initialize a Raphael Paper instance

    master

    To use Raphaël, you first need to create a Paper instance. This instance acts as the container for all your vector graphics and manages the drawing surface (SVG or VML depending on the browser).

    Pass the ID of an HTML element (or the element itself) to the Raphael() constructor to define where the graphics will be rendered.

    // Create a paper instance in a specific div
    var paper = Raphael("container", 500, 500);
  5. Load Raphaël via AMD

    master

    Raphaël is UMD compliant and can be loaded using an AMD loader (like RequireJS). Use the define function to import the library path and access the Raphael object within your module.

    define([ "path/to/raphael" ], function( Raphael ) {
      console.log( Raphael );
    });
  6. Remove shapes and clear the canvas

    master

    To remove a specific shape from the canvas, call its .remove() method. To clear all elements from the entire paper, use the paper.clear() method.

    Calling .remove() on a shape makes it inaccessible and cleans up its associated event listeners and DOM nodes.

    var rect = paper.rect(10, 10, 50, 50);
    
    // Remove a single shape
    rect.remove();
    
    // Clear the entire paper
    paper.clear();
  7. Manage Z-order with .toFront(), .toBack(), .insertAfter(), and .insertBefore()

    master

    You can control the stacking order of shapes in the canvas:

    • .toFront(): Moves the shape to the top of the stack (closest to the user).
    • .toBack(): Moves the shape to the bottom of the stack.
    • .insertAfter(otherShape): Places this shape immediately after otherShape in the DOM/stack.
    • .insertBefore(otherShape): Places this shape immediately before otherShape in the DOM/stack.
    var rect = paper.rect(10, 10, 50, 50);
    var circle = paper.circle(20, 20, 30);
    
    rect.toFront();
    circle.insertAfter(rect);
  8. Transform shapes using .transform(), .rotate(), .scale(), and .translate()

    master

    Raphaël provides high-level methods for geometric transformations on shape objects:

    • .transform(transformString): Applies a transformation using a string format (e.g., 's2,2t10,10').
    • .rotate(angle, [cx, cy]): Rotates the shape by angle degrees. If cx and cy are omitted, it rotates around the center of the shape's bounding box.
    • .scale(x, [y], [cx, cy]): Scales the shape by factor x (and optionally y) around a center point.
    • .translate(x, [y]): Moves the shape by the specified offsets.

    These methods are chainable and modify the shape's internal transformation matrix.

    var rect = paper.rect(10, 10, 50, 50);
    
    rect.rotate(45, 35, 35)
        .scale(2, 2)
        .translate(100, 100);
  9. Manipulate shape attributes with .attr()

    master

    Every shape returned by the Paper API has an .attr() method. This method is used to get or set attributes of the shape.

    To set attributes: Pass an object containing the attribute names and values. To get attributes: Pass a single string representing the attribute name. To set multiple attributes at once: Pass an object.

    Common attributes include:

    • fill: Color or gradient.
    • stroke: Color of the outline.
    • stroke-width: Thickness of the outline.
    • opacity: Transparency (0 to 1).
    • transform: CSS-like transformations (scale, rotate, translate).
    • cx, cy, r, x, y, width, height, etc., depending on the shape type.
    var circle = paper.circle(100, 100, 50);
    
    // Set multiple attributes
    circle.attr({
        fill: '#f00',
        stroke: '#000',
        'stroke-width': 2,
        opacity: 0.5
    });
    
    // Get a single attribute
    var currentFill = circle.attr('fill');
  10. Create vector shapes with the Paper API

    master

    The Paper instance provides methods to create various vector shapes. Each method returns a shape object that can be manipulated using the .attr() method.

    Supported shapes include:

    • circle(x, y, r): A circle at x, y with radius r.
    • rect(x, y, width, height, [rx, ry]): A rectangle at x, y with width and height. Optional rx and ry provide corner rounding.
    • ellipse(cx, cy, rx, ry): An ellipse centered at cx, cy with horizontal radius rx and vertical radius ry.
    • path(pathString): A complex shape defined by an SVG path string.
    • image(url, x, y, width, height): An image placed at x, y with specified dimensions.
    • text(x, y, text): A text element at x, y containing the provided string.
    var paper = Raphael('container');
    
    var circle = paper.circle(100, 100, 50);
    var rect = paper.rect(10, 10, 100, 50, 5);
    var ellipse = paper.ellipse(200, 200, 40, 20);
    var path = paper.path('M10,10L90,90');
    var img = paper.image('image.png', 50, 50, 100, 100);
    var txt = paper.text(100, 100, 'Hello World');
  11. Choose the correct Raphaël distributable file

    master

    Raphaël provides several UMD-compliant files depending on whether you want to include the required dependency eve and whether you need a minified version:

    • raphael.min.js: Includes eve, minified.
    • raphael.js: Includes eve, not minified.
    • raphael.no-deps.js: Does not include eve, not minified.
    • raphael.no-deps.min.js: Does not include eve, minified.

    Note: If you use a no-deps version, you must provide the eve dependency yourself.

  12. Apply visual effects with blur() and glow()

    master

    Raphaël provides built-in methods for common visual effects:

    • blur(radius): Applies a Gaussian blur filter to the element. Pass a numeric value for the radius. Calling blur(0) or removing the attribute removes the effect.
    • glow(options): Creates a glowing effect around the element by drawing multiple paths with increasing stroke widths and decreasing opacity.

    Glow Options:

    • width: The width of the glow.
    • fill: Boolean, whether to use a fill color.
    • opacity: The opacity of the glow.
    • offsetx / offsety: The offset of the glow.
    • color: The color of the glow.
    // Apply a blur
    element.blur(5);
    
    // Apply a glow
    element.glow({ width: 10, color: '#ff0000', opacity: 0.5 });