Painterro

repository·master·Indexed 20 days ago

https://github.com/devforth/painterro

A lightweight, vanilla JavaScript HTML5 image editing widget (js paint plugin) for in-browser image editing. It allows users to paste, crop, draw, annotate, and filter images directly within a web application. Version 1.2.92 supports npm installation, script tag integration, and a public API for controlling visibility, tool settings, and image scaling.

Tokens
5.6K
Snippets
15
Records
20
Agent score
71%

What's inside painterro

  1. Build Painterro from Source

    master

    To build the library for production use:

    1. Ensure you are using Node.js 16.
    2. Install dependencies:
      cd painterro
      npm ci
    3. Run the build command:
      npm run build

    Build Outputs

    • build/painterro.min.js: The var version for <script> tag imports.
    • build/painterro.commonjs2.js: Suitable for require/import in Webpack/bundlers.
    • build/painterro.amd.js & build/painterro.umd.js: For AMD/UMD importers.
    npm run build
  2. Install Painterro via script tag

    master

    You can include Painterro directly in your HTML by downloading the latest painterro-*.min.js from the GitHub releases and adding a <script> tag to your <head> section.

    To launch the widget, call Painterro().show() within your script (e.g., in an onclick handler or the body section).

    <!-- In <head> -->
    <script src="/xxx/painterro-x.x.x.min.js"></script>
    
    <!-- In <body> or an event handler -->
    <script>
      Painterro().show()
    </script>
  3. Install Painterro via npm

    master

    For npm-based projects (such as React, Vue, or Angular SPAs), install the painterro package using the following command:

    npm install painterro --save

    To use it in your code, import the module and call the show() method on the initialized instance.

    import Painterro from 'painterro'
    
    // Initialize and show the widget
    Painterro().show()
  4. Translate Painterro

    master

    Using Built-in Languages

    Pass the language parameter with an ISO 639-1 code (e.g., 'es' for Spanish, 'de' for German).

    Painterro({
      language: 'es'
    }).show();

    Custom Translations

    If you want to provide custom strings without contributing to the repo, use the translation parameter:

    Painterro({
      translation: {
        name: 'ua',
        strings: {
          apply: 'Застосувати'
        }
      }
    }).show();
  5. Implement a Save Handler

    master

    Painterro requires a saveHandler to persist images. You can save via binary multipart/form-data (most efficient) or base64 JSON.

    Use image.asBlob() to send data via FormData.

    var ptro = Painterro({
      saveHandler: function (image, done) {
        var formData = new FormData();
        formData.append('image', image.asBlob());
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://127.0.0.1:5000/save-as-binary/', true);
        xhr.onload = xhr.onerror = function () {
          done(true); // true hides painterro, false keeps it open
        };
        xhr.send(formData);
      }
    });
    ptro.show();

    Base64 Saving

    Use image.asDataURL() to send a base64 string via JSON.

    var ptro = Painterro({
        saveHandler: function (image, done) {
          var xhr = new XMLHttpRequest();
          xhr.open("POST", "http://127.0.0.1:5000/save-as-base64/");
          xhr.setRequestHeader("Content-Type", "application/json");
          xhr.send(JSON.stringify({
            image: image.asDataURL()
          }));
          xhr.onload = function (e) {
            done(true);
          }
        }
    });
    ptro.show();

    Smart Format Selection

    To optimize file size, you can check for an alpha channel and choose between PNG and JPEG:

    var ptro = Painterro({
      saveHandler: function (image, done) {
        const type = image.hasAlphaChannel() ? 'image/png' : 'image/jpeg';
        const blob = image.asBlob(type);
        // upload blob...
      }
    });
    var ptro = Painterro({
      saveHandler: function (image, done) {
        var formData = new FormData();
        formData.append('image', image.asBlob());
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://127.0.0.1:5000/save-as-binary/', true);
        xhr.onload = xhr.onerror = function () {
          done(true);
        };
        xhr.send(formData);
      }
    });
    ptro.show();
  6. Configure Painterro options

    master

    You can customize the behavior and appearance of the Painterro widget by passing a configuration object to the Painterro() constructor.

    Important Note on Positioning: If you provide an id to place Painterro inside a specific HTML element, ensure that the container element has a CSS position of relative, absolute, or fixed. The default static position may cause layout issues.

    Painterro({
      activeColor: '#00ff00', // default brush color is green
      // ... other params
    })
  7. Customize the UI Color Scheme

    master

    You can customize the Painterro interface colors by providing a colorScheme object during initialization. These settings affect the panels, controls, and inputs.

    Painterro({
      colorScheme: {
        main: '#fdf6b8', // light-yellow panels
        control: '#FECF67' // control background
      }
    }).show();
    Painterro({
      colorScheme: {
        main: '#fdf6b8',
        control: '#FECF67'
      }
    }).show();
  8. Initialize Painterro with PainterroProc

    master

    To use Painterro, instantiate the PainterroProc class. You must provide a params object. If an id is not provided in params, Painterro will automatically generate a unique ID and append a new container to the document.body.

    Key configuration options in params include:

    • id: The ID of the HTML element where Painterro should be mounted.
    • defaultTool: The name of the tool to activate by default.
    • hiddenTools: An array of tool names to hide from the UI.
    • saveHandler: A callback function triggered when the user clicks 'save'. It receives an imageSaver object and a callback to signal completion.
    • onChange: A callback triggered when changes occur, receiving an object with image (an imageSaver), operationsDone, and realesedMemoryOperations.
    const painterro = new PainterroProc({
      id: 'my-editor-id',
      defaultTool: 'brush',
      saveHandler: (imageSaver, done) => {
        // Handle the saved image
        const dataUrl = imageSaver.asDataURL('image/png');
        console.log('Saved image:', dataUrl);
        
        // Call done(true) to hide the editor, or done(false) to keep it open
        done(true);
      },
      onChange: ({ image, operationsDone }) => {
        console.log(`Operations completed: ${operationsDone}`);
      }
    });
  9. Open Painterro via Paste (Ctrl+V)

    master

    You can intercept the paste event to open Painterro with the clipboard content.

    document.onpaste = (event) => {
      const { items } = event.clipboardData || event.originalEvent.clipboardData;
      Array.from(items).forEach((item) => {
        if (item.kind === 'file') {
          if (!window.painterroOpenedInstance) {
            const blob = item.getAsFile();
            const reader = new FileReader();
            reader.onload = (readerEvent) => {
                window.painterroOpenedInstance = Painterro({
                  onHide: () => {
                    window.painterroOpenedInstance = undefined;
                  },
                  saveHandler: (image, done) => {
                    console.log('Save it here', image.asDataURL());
                    done(true);
                  },
                }).show(readerEvent.target.result, item.type);
            };
            reader.readAsDataURL(blob);
          }
        }
      });
    };
  10. Use the Painterro Public API

    master

    The Painterro instance provides methods to control visibility, tool settings, and image manipulation.

    Core Methods

    • .show([openImage, initialMimeType]): Shows the instance. openImage can be false (reopen last), a URL string, or any other value to clear content. initialMimeType helps identify the file type.
    • .hide(): Hides the instance.
    • .save(): Programmatically triggers the save process.
    • .setZoom(zoomPercentage): Sets the current zoom level.

    Tool Customization

    • .setColor(options): Sets the color for line or bg targets. options is [target, colorWidgetState] where colorWidgetState is { palleteColor, alpha, alphaColor }.
    • .setLineWidth(): Sets line width.
    • .setArrowLength(): Sets arrow width.
    • .setEraserWidth(): Sets eraser width.
    • .setShadowOn(boolean): Enables/disables shadow for lines or arrows.

    Image Scaling

    • .doScale({ width, height, scale }):
      • Match width: .doScale({width: 100})
      • Fill width and height: .doScale({width: 11, height: 15})
      • Scale factor: .doScale({ scale: 2 })
    var p = Painterro();
    p.show();
  11. Configure Painterro Events

    master

    Painterro provides several event hooks to react to user actions. Use these to handle saving, closing, or undo/redo operations.

    Event Reference

    EventArgumentsDescription
    onBeforeClosehasUnsavedChaged: bool, doCloseCallback: functionCalled before closing. Call doCloseCallback() to confirm close.
    onCloseundefinedTriggered when closed via the X button.
    onHideundefinedTriggered whenever the instance hides (X button, save, etc).
    onChange{<exportable image>}Called when something changes (paint, erase, resize).
    onUndo{<current history state>}Called on Ctrl+Z.
    onRedo{<current history state>}Called on Ctrl+Y (redo).
    onImageFailedOpenundefinedCalled if an image fails to load.
    onImageLoadedundefinedCalled when an image passed to .show() is loaded.
    saveHandler{<exportable image>}, doneCallback: functionCalled when user presses Save or Ctrl+S. Call doneCallback() to signal completion.

    Argument Shapes

    {<exportable image>}

    {
      image: {
       asBlob: (type, quality) => Blob,
       asDataURL: (type, quality) => string,
       suggestedFileName: (type) => string,
       hasAlphaChannel: () => boolean,
       getOriginalMimeType: () => string,
       getWidth: () => number,
       getHeight: () => number
      }
      operationsDone: number
    }

    {<current history state>}

    {
      prev: <history state> | undefined,
      next: <history state> | undefined,
      prevCount: number,
      sizeh: number,
      sizew: number
    }
  12. Configure Painterro via params

    master

    The PainterroProc constructor accepts a params object to customize the editor's behavior and appearance.

    Commonly used keys:

    • id: (string) The ID of the target element.
    • defaultTool: (string) The tool name to activate on startup.
    • hiddenTools: (string[]) Array of tool names to exclude from the toolbar.
    • saveHandler: (function) (imageSaver, done) => void. Required to handle saving logic.
    • onBeforeClose: (function) (hasUnsaved, doClose) => void. Allows intercepting the close action (e.g., to show a 'Save changes?' dialog).
    • onClose: (function) () => void. Called when the editor is closed.
    • onChange: (function) ({ image, operationsDone, realesedMemoryOperations }) => void.
    • styles: (string) Custom CSS to be injected into the editor.
    • backplateImgUrl: (string) URL of an image to use as a background for the canvas.
    • customTools: (Array<{name: string, callBack: Function, iconUrl?: string}>) Allows adding custom tools to the toolbar.