### Install and Initialize Painterro
Source: https://github.com/devforth/painterro/blob/master/README.md
Demonstrates how to install the package via npm and initialize the editor in a JavaScript environment.
```bash
npm install painterro --save
```
```javascript
import Painterro from 'painterro';
Painterro().show();
```
--------------------------------
### Install and Initialize Painterro
Source: https://context7.com/devforth/painterro/llms.txt
Demonstrates how to install the library via npm or include it via a script tag, followed by basic initialization to display the editor.
```bash
npm install painterro --save
```
```javascript
import Painterro from 'painterro';
// Basic initialization and display
Painterro().show();
```
```html
```
--------------------------------
### Install Node Modules for Painterro
Source: https://github.com/devforth/painterro/blob/master/README.md
This bash command installs the necessary Node.js dependencies for the Painterro project after cloning the repository. It navigates into the `painterro` directory and then runs `npm ci`, which performs a clean install based on the `package-lock.json` file, ensuring reproducible builds.
```bash
cd painterro
npm ci
```
--------------------------------
### Start Hot-Reload Dev Server (Bash)
Source: https://github.com/devforth/painterro/blob/master/README.md
Starts the hot-reload development server for Painterro, allowing for live code updates. Access the demo page at http://localhost:3000.
```bash
npm run dev
```
--------------------------------
### Configure Painterro Instance
Source: https://github.com/devforth/painterro/blob/master/README.md
Example of passing a configuration object to the Painterro constructor to customize default settings like brush color.
```javascript
Painterro({
activeColor: '#00ff00' // default brush color is green
});
```
--------------------------------
### Install Node.js Version 16 using NVM
Source: https://github.com/devforth/painterro/blob/master/README.md
This bash command installs Node.js version 16 using the Node Version Manager (nvm). This is often required for development or building projects that rely on specific Node.js versions. After installation, `nvm use 16` switches the current shell to use this version.
```bash
nvm install 16
nvm use 16
```
--------------------------------
### Install ESLint Import Plugin (NPM)
Source: https://github.com/devforth/painterro/blob/master/README.md
Installs the 'eslint-plugin-import' package, which is often required for projects using ESLint to properly handle module imports. This is a prerequisite for configuring ESLint to ignore compiled Painterro files.
```bash
npm i eslint-plugin-import
```
--------------------------------
### Initialize TinyMCE with Painterro Plugin
Source: https://github.com/devforth/painterro/blob/master/example/templates/paste_to_tinymce.html
Configures TinyMCE to include a custom 'painterro' button in the toolbar. The setup function registers a command that triggers the Painterro instance display.
```javascript
tinymce.init({
selector: 'textarea',
plugins: ['fullscreen'],
toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | table | fontsizeselect | painterro',
height: "700",
setup: function(editor) {
editor.addButton("painterro", {
title: "Open Painterro",
cmd: "painterro_cmd",
'icon': "painterro ptro-icon ptro-icon-painterro"
});
editor.addCommand("painterro_cmd", function () {
ptro.show();
});
}
});
```
--------------------------------
### Image Saving Handlers
Source: https://github.com/devforth/painterro/blob/master/README.md
Provides examples for implementing custom save handlers using both binary and base64 encoding.
```APIDOC
## Image Saving Handlers
### Description
Implement custom logic to handle the saving of the image. This involves providing a `saveHandler` function during Painterro initialization.
### Binary Saving
#### Method
`saveHandler: function(image, done)`
#### Parameters
- **image** (object) - An object representing the image data. Use `image.asBlob()` to get the image as a Blob.
- **done** (function) - Callback function to signal completion. Call `done(true)` to hide Painterro after saving, or `done(false)` to keep it open.
#### Request Example (JavaScript)
```js
var ptro = Painterro({
saveHandler: function (image, done) {
var formData = new FormData();
formData.append('image', image.asBlob());
// Optional: append suggested filename
// formData.append('image', image.asBlob(), image.suggestedFileName());
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://127.0.0.1:5000/save-as-binary/', true);
xhr.onload = xhr.onerror = function () {
done(true); // Hide Painterro after saving
};
xhr.send(formData);
}
})
ptro.show();
```
#### Backend Example (Python Flask)
```python
from flask import Flask, request, jsonify
import os
from time import time
app = Flask(__name__)
# Assume get_tmp_dir() and other necessary functions are defined
def get_tmp_dir():
return './tmp' # Example temporary directory
@app.route("/save-as-binary/", methods=['POST'])
def binary_saver():
filename = '{:10d}.png'.format(int(time())) # generate some filename
filepath = os.path.join(get_tmp_dir(), filename)
request.files['image'].save(filepath)
return jsonify({})
if __name__ == '__main__':
os.makedirs(get_tmp_dir(), exist_ok=True)
app.run(debug=True)
```
### Base64 Saving
#### Method
`saveHandler: function(image, done)`
#### Description
Similar to binary saving, but the image is encoded as a base64 string and sent via a JSON POST request. Note that base64 encoding is less efficient than binary transfer.
#### Request Example (JavaScript)
```js
var ptro = Painterro({
saveHandler: function (image, done) {
// Implementation for base64 saving would go here
// Typically involves getting image data as base64 and sending via JSON POST
// Example: image.asDataURL() or similar method to get base64 string
// fetch('/save-as-base64/', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({ imageData: base64String })
// }).then(response => {
// done(true);
// }).catch(error => {
// console.error('Error saving image:', error);
// done(false);
// });
}
})
ptro.show();
```
### Response
#### Success Response (200)
Image is saved according to the implemented handler logic.
#### Response Example
None
```
--------------------------------
### Implement Binary Save Handler
Source: https://github.com/devforth/painterro/blob/master/README.md
Configures a custom save handler to upload images as binary data using FormData and XMLHttpRequest. Includes a corresponding Python Flask backend example for processing the multipart request.
```javascript
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();
```
```python
@app.route("/save-as-binary/", methods=['POST'])
def binary_saver():
filename = '{:10d}.png'.format(int(time()))
filepath = os.path.join(get_tmp_dir(), filename)
request.files['image'].save(filepath)
return jsonify({})
```
--------------------------------
### Handle Image Saving with saveHandler
Source: https://context7.com/devforth/painterro/llms.txt
Provides an example of implementing the saveHandler callback to process edited images, such as converting them to Blobs and uploading them to a server via fetch.
```javascript
const ptro = Painterro({
saveHandler: function(image, done) {
const formData = new FormData();
formData.append('image', image.asBlob('image/png'));
fetch('/api/upload', {
method: 'POST',
body: formData
})
.then(() => done(true))
.catch(() => done(false));
}
});
ptro.show();
```
--------------------------------
### Save Images from Painterro to Python Flask Backend
Source: https://context7.com/devforth/painterro/llms.txt
Provides a Python Flask server example for receiving and saving images edited with Painterro. It demonstrates two methods: handling multipart/form-data uploads (binary) and processing base64 encoded image data sent via JSON. Assumes an upload folder exists.
```python
# server.py
import base64
import os
from time import time
from flask import Flask, request, jsonify
app = Flask(__name__)
UPLOAD_FOLDER = '/tmp/images'
@app.route('/save-binary', methods=['POST'])
def save_binary():
"""Handle multipart/form-data upload (most efficient)"""
if 'image' not in request.files:
return jsonify({'error': 'No image provided'}), 400
file = request.files['image']
filename = f'{int(time())}.png'
filepath = os.path.join(UPLOAD_FOLDER, filename)
file.save(filepath)
return jsonify({'filename': filename, 'path': filepath})
@app.route('/save-base64', methods=['POST'])
def save_base64():
"""Handle JSON base64 upload"""
data = request.json
if 'image' not in data:
return jsonify({'error': 'No image provided'}), 400
# Remove data URL prefix
base64_data = data['image'].split(',')[1]
filename = f'{int(time())}.png'
filepath = os.path.join(UPLOAD_FOLDER, filename)
with open(filepath, 'wb') as f:
f.write(base64.b64decode(base64_data))
return jsonify({'filename': filename, 'path': filepath})
if __name__ == '__main__':
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.run(port=5000)
```
--------------------------------
### doScale() Method
Source: https://context7.com/devforth/painterro/llms.txt
Scales the current image to specified dimensions or by a scale factor. This method is useful for resizing images, for example, before saving them to a specific resolution or to reduce file size. You can scale to exact dimensions, a specific width or height (maintaining aspect ratio), or by a multiplier.
```APIDOC
## doScale() Method
### Description
Scales the current image to specified dimensions or by a scale factor. Useful for resizing images before saving.
### Method
`ptro.doScale(options: object)`
### Parameters
#### Query Parameters
- **options** (object) - An object containing scaling parameters. Specify one of the following:
- **width** (number) - The target width in pixels. Height will be calculated proportionally.
- **height** (number) - The target height in pixels. Width will be calculated proportionally.
- **width** (number) and **height** (number) - Target width and height in pixels. Aspect ratio may be distorted.
- **scale** (number) - A scaling factor (e.g., 2 for 2x enlargement, 0.5 for 50% reduction).
### Request Example
```javascript
// Scale to a width of 800 pixels
ptro.doScale({ width: 800 });
// Scale to a height of 600 pixels
ptro.doScale({ height: 600 });
// Scale to exact dimensions 800x600 pixels
ptro.doScale({ width: 800, height: 600 });
// Scale up by a factor of 2
ptro.doScale({ scale: 2 });
// Scale down to 50%
ptro.doScale({ scale: 0.5 });
```
```
--------------------------------
### Get Image as Blob (JavaScript)
Source: https://context7.com/devforth/painterro/llms.txt
The asBlob method returns the image as a Blob object, suitable for efficient binary uploads. It allows smart format selection based on the alpha channel and supports quality parameters for formats like JPEG. The Blob can then be uploaded using XMLHttpRequest or Fetch API.
```javascript
const ptro = Painterro({
saveHandler: function(image, done) {
// Smart format selection based on alpha channel
const hasAlpha = image.hasAlphaChannel();
const mimeType = hasAlpha ? 'image/png' : 'image/jpeg';
const quality = hasAlpha ? undefined : 0.85;
const blob = image.asBlob(mimeType, quality);
console.log('Blob size:', blob.size, 'bytes');
console.log('Blob type:', blob.type);
console.log('Original MIME:', image.getOriginalMimeType());
// Upload using XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload', true);
xhr.onload = () => done(true);
xhr.onerror = () => done(false);
const formData = new FormData();
formData.append('file', blob, image.suggestedFileName(mimeType.split('/')[1]));
xhr.send(formData);
}
});
```
--------------------------------
### Save Image as PNG or JPEG based on Alpha Channel
Source: https://github.com/devforth/painterro/blob/master/README.md
This JavaScript code provides an efficient way to save images by checking for an alpha channel. If the image has transparency, it's saved as 'image/png'; otherwise, it's saved as 'image/jpeg' to reduce file size. The `image.asBlob()` method is used to get the image data as a Blob object.
```javascript
var ptro = Painterro({
saveHandler: function (image, done) {
image.asBlob(image.hasAlphaChannel() ? 'image/png' : 'image/jpeg');
// upload blob
}
})
```
--------------------------------
### Get Image as Data URL (JavaScript)
Source: https://context7.com/devforth/painterro/llms.txt
The asDataURL method returns the image as a base64-encoded data URL string. It supports specifying the MIME type and quality for formats like JPEG and WebP. This is useful for embedding images directly or sending them via JSON APIs.
```javascript
const ptro = Painterro({
saveHandler: function(image, done) {
// Get as PNG (default)
const pngDataUrl = image.asDataURL();
// Get as JPEG with 80% quality
const jpegDataUrl = image.asDataURL('image/jpeg', 0.8);
// Get as WebP with 90% quality
const webpDataUrl = image.asDataURL('image/webp', 0.9);
// Send via JSON API
fetch('/api/save-image', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
image: jpegDataUrl,
width: image.getWidth(),
height: image.getHeight()
})
})
.then(() => done(true));
}
});
```
--------------------------------
### Painterro Configuration and Initialization
Source: https://github.com/devforth/painterro/blob/master/README.md
Demonstrates how to initialize Painterro with basic options and how to set language and custom translations.
```APIDOC
## Painterro Initialization
### Description
Initializes the Painterro instance and shows the editor.
### Method
`Painterro(options)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
**options** (object) - Optional configuration object.
- **language** (string) - Sets the language for the Painterro UI (e.g., 'es' for Spanish).
- **translation** (object) - Allows for custom translations or overriding existing ones.
- **name** (string) - The name of the translation set.
- **strings** (object) - An object containing key-value pairs for strings to be translated.
### Request Example
```js
var p = Painterro({
language: 'es' // Spanish
}).show()
// Example with custom translations
var ptro = Painterro({
translation: {
name: 'ua',
strings: {
apply: 'Застосувати'
// other strings
}
}
}).show()
```
### Response
#### Success Response (200)
Painterro instance is initialized and shown.
#### Response Example
None
```
--------------------------------
### Initialize and Configure Painterro Instance
Source: https://github.com/devforth/painterro/blob/master/build/index.html
Demonstrates how to instantiate the Painterro editor with custom language settings, color schemes, and save handlers. It also shows how to programmatically trigger the editor display and listen for tool change events.
```javascript
window.p = Painterro({
language: 'uk',
backgroundFillColorAlpha: 0,
hideByEsc: true,
colorScheme: {
main: '#8B817A',
control: '#1A1A1A',
controlContent: '#fff',
controlShadow: 'none',
activeControl: '#6F6762',
activeControlContent: '#fff',
hoverControl: '#6F6762',
hoverControlContent: '#fff'
},
saveHandler: this._onPainterroSave
});
window.p.show();
const el = document.getElementById('app');
el.addEventListener('changeActiveTool', (e) => {
console.log('activeToolHasBeenCHanged', e);
});
```
--------------------------------
### Initialize and Localize Painterro
Source: https://github.com/devforth/painterro/blob/master/README.md
Demonstrates how to instantiate the Painterro editor and apply language settings. Users can either select a pre-defined language code or provide a custom translation object.
```javascript
var p = Painterro()
p.show()
Painterro({
language: 'es'
}).show()
Painterro({
translation: {
name: 'ua',
strings: {
apply: 'Застосувати'
}
}
}).show()
```
--------------------------------
### Configure Painterro Instance
Source: https://context7.com/devforth/painterro/llms.txt
Shows how to instantiate Painterro with a configuration object to customize UI elements, default tool settings, colors, and behavior.
```javascript
const ptro = Painterro({
activeColor: '#ff0000',
activeFillColor: '#000000',
defaultTool: 'brush',
hiddenTools: ['redo', 'zoomin', 'zoomout', 'rotate'],
toolbarPosition: 'bottom',
language: 'en'
});
ptro.show();
```
--------------------------------
### Instance Methods
Source: https://github.com/devforth/painterro/blob/master/README.md
Core methods to control the visibility and state of the Painterro instance.
```APIDOC
## Instance Methods
### .show([openImage], [initialMimeType])
Shows the painterro instance.
- **openImage**: Can be `false` (last state), a URL string, or other values to clear content.
- **initialMimeType**: Optional hint for file type handling.
### .hide()
Hides the current painterro instance.
### .setColor(options)
Sets the color of a specific tool.
- **options**: Array containing `[target, colorWidgetState]`.
- **target**: 'line' or 'bg'.
- **colorWidgetState**: Object containing `palleteColor` string.
```
--------------------------------
### UI Configuration
Source: https://github.com/devforth/painterro/blob/master/README.md
How to customize the Painterro user interface using the colorScheme object.
```APIDOC
## UI Configuration
### Description
Customize the look and feel of the Painterro interface by passing a `colorScheme` object during initialization.
### Request Example
```js
Painterro({
colorScheme: {
main: '#fdf6b8',
control: '#FECF67'
}
}).show()
```
### Parameters
- **main** (string) - Color of panels (default: '#fff')
- **control** (string) - Background color of controls (default: '#fff')
- **activeControl** (string) - Color for active controls (default: '#7485B1')
- **backgroundColor** (string) - Background color outside image area (default: '#999999')
```
--------------------------------
### Build Painterro Project
Source: https://github.com/devforth/painterro/blob/master/README.md
This bash command initiates the build process for the Painterro project using npm. The `npm run build` script typically compiles the ES6 code, transpiles it using Babel, and bundles it using webpack into optimized files located in the `build/` directory.
```bash
npm run build
```
--------------------------------
### Build Painterro for Development (Bash)
Source: https://github.com/devforth/painterro/blob/master/README.md
Builds the Painterro project from its source files. This command is typically run within the Painterro source folder and is often used in conjunction with a watcher for continuous development.
```bash
watch npm run build
```
--------------------------------
### Include Painterro via Script Tag
Source: https://github.com/devforth/painterro/blob/master/README.md
Shows how to include the Painterro library directly in an HTML file and trigger the editor instance.
```html
```
--------------------------------
### Painterro Methods for Tool Configuration
Source: https://github.com/devforth/painterro/blob/master/README.md
Details methods for configuring drawing tools like line width, arrow size, eraser width, and shadow effects.
```APIDOC
## Tool Configuration Methods
### Description
These methods allow you to adjust the properties of various drawing tools within Painterro.
### Methods
#### `.setLineWidth(width)`
Sets the line width for the currently selected tool.
- **width** (number) - The desired line width.
#### `.setArrowLength(length)`
Sets the width for arrows.
- **length** (number) - The desired arrow width.
#### `.setEraserWidth(width)`
Sets the width of the eraser.
- **width** (number) - The desired eraser width.
#### `.setShadowOn(enable)`
Enables or disables shadow effects for line or arrow elements.
- **enable** (boolean) - `true` to enable shadow, `false` to disable.
### Request Example
```js
// Assuming 'p' is an initialized Painterro instance
p.setLineWidth(5);
p.setArrowLength(20);
p.setEraserWidth(10);
p.setShadowOn(true);
```
### Response
#### Success Response (200)
Configuration is applied to the active tool.
#### Response Example
None
```
--------------------------------
### Configure Painterro UI Color Scheme
Source: https://github.com/devforth/painterro/blob/master/README.md
Demonstrates how to customize the Painterro user interface by passing a colorScheme object during initialization. This allows for simple theme adjustments using standard CSS color strings.
```javascript
Painterro({
colorScheme: {
main: '#fdf6b8',
control: '#FECF67'
}
}).show();
```
--------------------------------
### Manage Editor Visibility with show() and hide()
Source: https://context7.com/devforth/painterro/llms.txt
Explains how to programmatically control the editor's visibility. The show method supports loading images from URLs, while hide allows closing the interface without destroying the instance.
```javascript
const ptro = Painterro({ saveHandler: (image, done) => done(true) });
// Show with image from URL
ptro.show('https://example.com/image.png');
// Hide the editor
ptro.hide();
```
--------------------------------
### Initialize and Style Painterro
Source: https://github.com/devforth/painterro/blob/master/build/contained.html
Configures the CSS layout for the Painterro container and initializes the editor instance with custom background, image, and color scheme settings. The initialization requires a target DOM element ID and accepts various configuration objects to customize the UI appearance.
```css
html, body, #wrapper { height: 100%; margin: 0; padding: 0; background-color: lightgray; }
#conatiner { position: relative; height: 300px; width: 300px; }
```
```javascript
Painterro({
id: 'conatiner',
backgroundFillColor: '#eee',
backplateImg: 'https://images.pexels.com/photos/3653762/pexels-photo-3653762.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
colorScheme: {
main: '#faf',
control: '#d5d',
activeControl: '#572257',
inputBackground: '#cf99ca'
}
}).show();
```
--------------------------------
### Tool Configuration Methods
Source: https://context7.com/devforth/painterro/llms.txt
Provides methods to programmatically configure various drawing tool properties. This includes setting the line width for line-based tools, arrow length, eraser width, pixel size for the pixelization tool, and enabling or disabling shadows on primitive shapes.
```APIDOC
## Tool Configuration Methods
### Description
Methods to programmatically configure drawing tool properties including line width, arrow length, eraser width, and shadow settings.
### Methods
- **`ptro.setLineWidth(width: number)`**: Sets the line width for line, rectangle, ellipse, and brush tools.
- **`ptro.setArrowLength(length: number)`**: Sets the length of arrows for the arrow tool.
- **`ptro.setEraserWidth(width: number)`**: Sets the width of the eraser.
- **`ptro.setPixelSize(size: number)`**: Sets the pixel size for the pixelization tool.
- **`ptro.setShadowOn(enable: boolean)`**: Enables or disables shadow effects on primitive shapes.
### Request Example
```javascript
ptro.show();
// Set line width to 10 pixels
ptro.setLineWidth(10);
// Set arrow length to 50 pixels
ptro.setArrowLength(50);
// Set eraser width to 20 pixels
ptro.setEraserWidth(20);
// Set pixel size to 8 pixels
ptro.setPixelSize(8);
// Enable shadow on shapes
ptro.setShadowOn(true);
```
```
--------------------------------
### Add Custom Tools
Source: https://context7.com/devforth/painterro/llms.txt
Extends the toolbar with user-defined tools, providing an icon URL and a callback function to execute custom logic using the Painterro instance.
```javascript
const ptro = Painterro({
customTools: [
{
name: 'download',
iconUrl: 'data:image/svg+xml;base64,...',
callBack: function() {
const dataUrl = this.imageSaver.asDataURL('image/png');
// ... logic to trigger download
}
}
]
});
```
--------------------------------
### Import Painterro from Local Build (JavaScript)
Source: https://github.com/devforth/painterro/blob/master/README.md
Replaces the standard import statement for Painterro with a local path to the compiled commonjs2 file. This is necessary when integrating a locally built version of Painterro into your side application for development.
```javascript
import Painterro from '/home/ivan/devforth/painterro/build/painterro.commonjs2.js';
```
--------------------------------
### asBlob() Method
Source: https://context7.com/devforth/painterro/llms.txt
Returns the image as a Blob object, which is suitable for efficient binary uploads. This method supports format and quality parameters, allowing for optimized image handling. It's particularly useful when sending image data directly to a server without encoding it into a string.
```APIDOC
## asBlob() Method
### Description
Returns the image as a Blob object for efficient binary uploads. Supports format and quality parameters.
### Method
`image.asBlob([mimeType: string], [quality: number])`
### Parameters
#### Query Parameters
- **mimeType** (string) - Optional - The MIME type of the image format (e.g., 'image/png', 'image/jpeg'). The library may intelligently select this if not provided, based on image content.
- **quality** (number) - Optional - The quality of the image, ranging from 0.0 to 1.0. Only applicable for lossy formats like JPEG. Defaults to 1.0.
### Request Example
```javascript
const hasAlpha = image.hasAlphaChannel();
const mimeType = hasAlpha ? 'image/png' : 'image/jpeg';
const quality = hasAlpha ? undefined : 0.85;
const blob = image.asBlob(mimeType, quality);
```
### Response
#### Success Response (200)
- **blob** (Blob) - A Blob object representing the image data.
#### Response Example
```javascript
// Example of accessing Blob properties
console.log('Blob size:', blob.size, 'bytes');
console.log('Blob type:', blob.type);
```
```
--------------------------------
### Specify Image Format and Quality
Source: https://github.com/devforth/painterro/blob/master/README.md
This JavaScript snippet shows how to specify the image format (e.g., 'image/jpeg', 'image/png') and quality when saving an image from Painterro using `asDataURL()` or `asBlob()`. Quality can be set between 0.0 and 1.0 for JPEG and WebP formats. The default format is 'image/png' or the original image's format, and the default quality is 0.92.
```javascript
// Example for JPEG with quality 0.5
image.asDataURL('image/jpeg', 0.5);
// Example for PNG
image.asDataURL('image/png');
```
--------------------------------
### Image Manipulation Methods
Source: https://github.com/devforth/painterro/blob/master/README.md
Covers methods for saving, scaling, and zooming the image within Painterro.
```APIDOC
## Image Manipulation Methods
### Description
Methods for saving the current image, scaling it to specific dimensions, and adjusting the zoom level.
### Methods
#### `.save()`
Triggers the save action, equivalent to clicking the save button.
#### `.doScale({ width, height, scale })`
Scales the image and resizes the drawing area.
- **width** (number) - Target width for scaling. If only width is provided, height is scaled proportionally.
- **height** (number) - Target height for scaling. If both width and height are provided, the image is scaled to fit within these dimensions.
- **scale** (number) - A scaling factor (e.g., `2` for doubling the size).
**Examples:**
- Scale to match width (proportional height): `.doScale({ width: 100 })`
- Scale to fill width and height: `.doScale({ width: 11, height: 15 })`
- Scale by a factor of 2: `.doScale({ scale: 2 })`
#### `.setZoom(zoomPercentage)`
Sets the current zoom level of the image.
- **zoomPercentage** (number) - The desired zoom level as a percentage (e.g., 100 for 100%).
### Request Example
```js
// Assuming 'p' is an initialized Painterro instance
p.save();
p.doScale({ width: 100 }); // Scale to width 100, proportional height
p.setZoom(150); // Set zoom to 150%
```
### Response
#### Success Response (200)
Image is saved, scaled, or zoomed as requested.
#### Response Example
None
```
--------------------------------
### Regenerate Icons Font (Bash)
Source: https://github.com/devforth/painterro/blob/master/README.md
Executes a build script to regenerate the icon font for Painterro. This command should be run after making any changes to the icon files located in the 'res' folder.
```bash
npm run buildfont
```
--------------------------------
### Painterro Events
Source: https://github.com/devforth/painterro/blob/master/README.md
List of available event hooks for handling user interactions such as closing, saving, and image manipulation.
```APIDOC
## Events
### Description
Callbacks triggered during the lifecycle of the Painterro instance.
### Events List
- **onBeforeClose** (function) - Called when user closes painterro; arguments: `hasUnsavedChanged` (bool), `doCloseCallback` (function).
- **onClose** (function) - Triggered when closed via X button.
- **onHide** (function) - Triggered when painterro hides (any reason).
- **onChange** (function) - Triggered on any change (paint, erase, resize).
- **onUndo** (function) - Triggered on undo (Ctrl+Z).
- **onRedo** (function) - Triggered on redo (Ctrl+Z).
- **onImageFailedOpen** (function) - Triggered if image fails to load.
- **onImageLoaded** (function) - Triggered when image is successfully loaded.
- **saveHandler** (function) - Triggered on Save (Ctrl+S); arguments: `exportableImage`, `doneCallback`.
```
--------------------------------
### Configure Painterro Layout with CSS
Source: https://github.com/devforth/painterro/blob/master/build/index.html
Defines the basic CSS layout for the Painterro container, ensuring it occupies the available screen space with specific margins and positioning.
```css
html, body, #wrapper { height: 100%; margin: 0; padding: 0; background-color: white; }
#conatiner { position: absolute; top: 50px; bottom: 50px; left: 20px; right: 20px; }
#holder { display: flex; }
```
--------------------------------
### Handle Image Paste from Clipboard with JavaScript
Source: https://context7.com/devforth/painterro/llms.txt
Automatically opens Painterro when a user pastes an image via Ctrl+V. It checks clipboard items for image files and initiates the Painterro editor with the pasted image data. Requires the Painterro library to be included.
```javascript
let painterroInstance = null;
document.onpaste = (event) => {
const items = event.clipboardData?.items || event.originalEvent?.clipboardData?.items;
Array.from(items).forEach((item) => {
if (item.kind === 'file' && item.type.startsWith('image/')) {
if (!painterroInstance) {
const blob = item.getAsFile();
const reader = new FileReader();
reader.onload = (e) => {
painterroInstance = Painterro({
onHide: () => {
painterroInstance = null;
},
saveHandler: (image, done) => {
// Upload or process the image
console.log('Image ready:', image.asDataURL());
done(true);
}
}).show(e.target.result, item.type);
};
reader.readAsDataURL(blob);
}
}
});
};
```
--------------------------------
### Scale Image Programmatically (JavaScript)
Source: https://context7.com/devforth/painterro/llms.txt
The doScale method allows resizing the current image either to specific dimensions or by a scale factor. This is useful for adjusting image sizes before saving or for applying transformations. It supports scaling by width, height, exact dimensions, or a multiplier.
```javascript
const ptro = Painterro();
ptro.show('https://example.com/large-image.png');
// Scale to specific width (height calculated proportionally)
ptro.doScale({ width: 800 });
// Scale to specific height (width calculated proportionally)
ptro.doScale({ height: 600 });
// Scale to exact dimensions (may distort aspect ratio)
ptro.doScale({ width: 800, height: 600 });
// Scale by factor (2x enlargement)
ptro.doScale({ scale: 2 });
// Scale down to 50%
ptro.doScale({ scale: 0.5 });
```
--------------------------------
### POST /save-binary
Source: https://context7.com/devforth/painterro/llms.txt
Handles multipart/form-data image uploads from the Painterro saveHandler, providing an efficient way to save binary image data to the server.
```APIDOC
## POST /save-binary
### Description
Receives a binary image file via multipart/form-data and saves it to the server storage.
### Method
POST
### Endpoint
/save-binary
### Parameters
#### Request Body
- **image** (file) - Required - The binary image file to be uploaded.
### Request Example
Content-Type: multipart/form-data
### Response
#### Success Response (200)
- **filename** (string) - The generated name of the saved file.
- **path** (string) - The absolute path where the file is stored.
#### Response Example
{
"filename": "1678901234.png",
"path": "/tmp/images/1678901234.png"
}
```
--------------------------------
### Open Painterro on Ctrl+V Paste
Source: https://github.com/devforth/painterro/blob/master/README.md
This JavaScript code enables opening Painterro when an image is pasted into the document using Ctrl+V. It intercepts the paste event, checks for file items, reads the pasted image as a Data URL, and then initializes and shows a new Painterro instance with the pasted image. It also handles closing Painterro and resetting the instance variable.
```javascript
document.onpaste = (event) => {
const { items } = event.clipboardData || event.originalEvent.clipboardData;
Array.from(items).forEach((item) => {
if (item.kind === 'file') {
if (!window.painterroOpenedInstance) {
// if painterro already opened - it will handle onpaste
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()); // you could provide your save handler
done(true);
},
}).show(readerEvent.target.result, item.type);
};
reader.readAsDataURL(blob);
}
}
});
};
```
--------------------------------
### asDataURL() Method
Source: https://context7.com/devforth/painterro/llms.txt
Returns the image as a base64-encoded data URL string. This method is useful for embedding images directly into HTML or sending them via JSON APIs. You can specify the desired image format (e.g., 'image/jpeg', 'image/webp') and quality.
```APIDOC
## asDataURL() Method
### Description
Returns the image as a base64-encoded data URL string. Useful for embedding images directly or sending via JSON APIs.
### Method
`image.asDataURL([mimeType: string], [quality: number])`
### Parameters
#### Query Parameters
- **mimeType** (string) - Optional - The MIME type of the image format (e.g., 'image/png', 'image/jpeg', 'image/webp'). Defaults to 'image/png'.
- **quality** (number) - Optional - The quality of the image, ranging from 0.0 to 1.0. Only applicable for lossy formats like JPEG and WebP. Defaults to 1.0.
### Request Example
```javascript
const pngDataUrl = image.asDataURL();
const jpegDataUrl = image.asDataURL('image/jpeg', 0.8);
const webpDataUrl = image.asDataURL('image/webp', 0.9);
```
### Response
#### Success Response (200)
- **dataUrl** (string) - The base64-encoded data URL string of the image.
#### Response Example
```
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
```
```
--------------------------------
### setColor() Method
Source: https://context7.com/devforth/painterro/llms.txt
Programmatically sets the color for various drawing tools. This method takes an array where the first element specifies the target tool ('line', 'fill', 'bg') and the second element is an object containing the color state, including palette color, alpha, and RGBA string representation.
```APIDOC
## setColor() Method
### Description
Programmatically sets the color for drawing tools. Takes an array with target and color state object.
### Method
`ptro.setColor([target: string, colorState: object])`
### Parameters
#### Path Parameters
- **target** (string) - Required - The tool to set the color for. Possible values: 'line', 'fill', 'bg'.
- **colorState** (object) - Required - An object containing the color properties:
- **palleteColor** (string) - The color in hexadecimal format (e.g., '#0000ff').
- **alpha** (number) - The opacity of the color, from 0.0 to 1.0.
- **alphaColor** (string) - The color represented as an RGBA string (e.g., 'rgba(0, 0, 255, 0.8)').
### Request Example
```javascript
// Set line color to blue with 80% opacity
ptro.setColor(['line', {
palleteColor: '#0000ff',
alpha: 0.8,
alphaColor: 'rgba(0, 0, 255, 0.8)'
}]);
// Set fill color to green with 50% opacity
ptro.setColor(['fill', {
palleteColor: '#00ff00',
alpha: 0.5,
alphaColor: 'rgba(0, 255, 0, 0.5)'
}]);
// Set background color to white
ptro.setColor(['bg', {
palleteColor: '#ffffff',
alpha: 1.0,
alphaColor: 'rgba(255, 255, 255, 1.0)'
}]);
```
```
--------------------------------
### Backend to Save Base64 Image
Source: https://github.com/devforth/painterro/blob/master/README.md
This Python Flask snippet shows a backend route that receives a Base64 encoded image from the frontend. It decodes the image data, converts it to binary, and saves it as a PNG file in a temporary directory. The filename is generated based on the current timestamp.
```python
@app.route("/save-as-base64/", methods=['POST'])
def base64_saver():
filename = '{:10d}.png'.format(int(time())) # generate some filename
filepath = os.path.join(get_tmp_dir(), filename)
with open(filepath, "wb") as fh:
base64_data = request.json['image'].replace('data:image/png;base64,', '')
fh.write(base64.b64decode(base64_data))
return jsonify({})
```
--------------------------------
### Save Image as Base64 using XHR
Source: https://github.com/devforth/painterro/blob/master/README.md
This JavaScript snippet demonstrates how to save an image from Painterro as a Base64 encoded string using XMLHttpRequest. The image data is sent as JSON to a specified backend endpoint. The backend is expected to decode the Base64 data and save it as a PNG file. The `done` callback is used to signal the completion of the save operation.
```javascript
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) {
// after saving is done, call done callback
done(true); //done(true) will hide painterro, done(false) will leave opened
}
```
--------------------------------
### Exportable Image Object Structure
Source: https://github.com/devforth/painterro/blob/master/README.md
Defines the structure of the exportable image object provided in event callbacks. It includes methods for blob conversion, data URL generation, and metadata retrieval.
```javascript
{
image: {
asBlob: (type, quality) => {},
asDataURL: (type, quality) => {},
suggestedFileName: (type) => {},
hasAlphaChannel: () => {},
getOriginalMimeType: () => {},
getWidth: () => {},
getHeight: () => {}
},
operationsDone: 0
}
```
--------------------------------
### Configure Painterro Save Handler
Source: https://github.com/devforth/painterro/blob/master/example/templates/paste_to_tinymce.html
Initializes the Painterro instance with default dimensions and a save handler. The handler converts the edited image to a data URL and inserts it into the active TinyMCE editor.
```javascript
var ptro = Painterro({
defaultSize: '500x400',
saveHandler: function (image, done) {
tinymce.activeEditor.execCommand('mceInsertContent', false, '
');
done(true);
}
});
```
--------------------------------
### Configure Drawing Tool Properties (JavaScript)
Source: https://context7.com/devforth/painterro/llms.txt
Painterro provides methods to programmatically configure drawing tool properties. These include setting line width, arrow length, eraser width, pixel size, and enabling/disabling shadows on primitive shapes.
```javascript
const ptro = Painterro();
ptro.show();
// Set line width for line, rectangle, ellipse, brush tools
ptro.setLineWidth(10);
// Set arrow length
ptro.setArrowLength(50);
// Set eraser width
ptro.setEraserWidth(20);
// Set pixel size for pixelization tool
ptro.setPixelSize(8);
// Enable/disable shadow on primitive shapes
ptro.setShadowOn(true);
```
--------------------------------
### Configure Custom Translations
Source: https://context7.com/devforth/painterro/llms.txt
Overrides default interface strings or sets the editor language to a built-in locale to support internationalization.
```javascript
const ptro = Painterro({
translation: {
name: 'custom',
strings: {
apply: 'Aplicar',
cancel: 'Cancelar',
tools: { crop: 'Recortar imagen' }
}
}
});
const ptroSpanish = Painterro({
language: 'es'
});
```
--------------------------------
### Scale Image Dimensions with Painterro
Source: https://github.com/devforth/painterro/blob/master/README.md
Adjusts the image dimensions and canvas area using width, height, or a scale factor. These methods allow for proportional scaling or specific dimension filling.
```javascript
.doScale({width: 100})
.doScale({width: 11, height: 15})
.doScale({ scale: 2 })
```
--------------------------------
### Configure ESLint Ignore (JSON)
Source: https://github.com/devforth/painterro/blob/master/README.md
Adds an 'eslintIgnore' property to your side application's 'package.json' file. This tells ESLint to skip linting the compiled Painterro commonjs2 file, preventing potential conflicts or errors.
```json
"eslintIgnore": [
"/home/ivan/devforth/painterro/build/painterro2.commonjs.js"
],
```
--------------------------------
### Handle Before Close Event (JavaScript)
Source: https://context7.com/devforth/painterro/llms.txt
The onBeforeClose event is called when the user attempts to close Painterro. It allows for implementing confirmation dialogs for unsaved changes before the editor is closed. The event handler receives a callback `doClose` to proceed with closing.
```javascript
const ptro = Painterro({
onBeforeClose: function(hasUnsavedChanges, doClose) {
if (hasUnsavedChanges) {
const confirmed = confirm('You have unsaved changes. Close anyway?');
if (confirmed) {
doClose(); // Proceed with closing
}
// Don't call doClose() to cancel closing
} else {
doClose(); // No changes, close immediately
}
},
onClose: function() {
console.log('Editor closed via X button');
},
onHide: function() {
console.log('Editor hidden (by any method)');
}
});
```
--------------------------------
### POST /save-base64
Source: https://context7.com/devforth/painterro/llms.txt
Handles JSON-encoded base64 image uploads, suitable for scenarios where images are transmitted as data URLs.
```APIDOC
## POST /save-base64
### Description
Receives a JSON object containing a base64 encoded image string, decodes it, and saves it to the server.
### Method
POST
### Endpoint
/save-base64
### Parameters
#### Request Body
- **image** (string) - Required - The base64 data URL of the image.
### Request Example
{
"image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
}
### Response
#### Success Response (200)
- **filename** (string) - The generated name of the saved file.
- **path** (string) - The absolute path where the file is stored.
#### Response Example
{
"filename": "1678901234.png",
"path": "/tmp/images/1678901234.png"
}
```
--------------------------------
### Integrate Painterro with TinyMCE Editor using JavaScript
Source: https://context7.com/devforth/painterro/llms.txt
Allows users to insert edited images directly into a TinyMCE rich text editor. It initializes Painterro and configures its saveHandler to insert the edited image as an `
` tag into the active TinyMCE editor. Requires TinyMCE and Painterro libraries.
```javascript
// TinyMCE integration
tinymce.init({ selector: 'textarea' });
const ptro = Painterro({
saveHandler: function(image, done) {
const dataUrl = image.asDataURL('image/png');
tinymce.activeEditor.execCommand(
'mceInsertContent',
false,
`
`
);
done(true);
}
});
document.getElementById('insertImage').onclick = () => {
ptro.show();
};
```
--------------------------------
### Handle Image Change Event (JavaScript)
Source: https://context7.com/devforth/painterro/llms.txt
The onChange event is triggered whenever the image is modified. It provides information about the operations performed and memory released. This event is useful for implementing auto-save functionality or displaying indicators for unsaved changes.
```javascript
const ptro = Painterro({
onChange: function(event) {
console.log('Operations done:', event.operationsDone);
console.log('Memory operations released:', event.realesedMemoryOperations);
// Access current image
const preview = event.image.asDataURL('image/jpeg', 0.5);
document.getElementById('preview').src = preview;
// Show unsaved indicator
document.getElementById('unsaved').style.display = 'block';
}
});
```