• Stars
    star
    1,541
  • Rank 30,174 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A small JS library for beautiful drawing and handwriting on the HTML Canvas.

Atrament

A small JS library for beautiful drawing and handwriting on the HTML Canvas


Build Status

Atrament is a library that enables the user to draw smooth, natural drawings and handwriting on the HTML canvas. The algorithm was originally developed about 2 weeks after I started learning JavaScript, as I wanted to build a collaborative drawing space on the web, which ended up being 1WALL. I wanted the drawing to feel natural and comfortable, and the result to be smooth and pleasing. Years later, I've taken the algorithm, improved it, rewrote it in ES6 and made it into a neat little library.

FEATURES:

  • Draw/Fill/Erase modes
  • Adjustable adaptive smoothing
  • Events tracking the drawing - this allows the app to "replay" or reconstruct the drawing, e.g. for undo functionality
  • Adjustable line thickness and colour

Here's a basic demo.

Enjoy!

Installation

as a module

If you're using a tool like webpack or browserify to bundle your code, you can install it using npm.

  • install atrament as a dependency using npm install --save atrament.
  • You can access the Atrament class using import { Atrament } from 'atrament';

script tag

Include the script located at dist/atrament.min.js in the <head> tag of your HTML.

Alternatively, you can use Bower: bower install atrament and include bower_components/atrament/dist/atrament.min.js as a script tag.

polymer

Thanks to rubenstolk, you can also use the sc-atrament Polymer element.

Usage

  • create a <canvas> tag, e.g.:
<canvas id="sketchpad" width="500" height="500"></canvas>
  • in your JavaScript, create an Atrament instance passing it your canvas object:
import { Atrament } from 'atrament';

const canvas = document.querySelector('#sketchpad');
const sketchpad = new Atrament(canvas);
  • you can also pass the width, height and default colour to the constructor:
const sketchpad = new Atrament(canvas, {
  width: 500,
  height: 500,
  color: 'orange',
});
  • that's it, happy drawing!

Options & config

  • clear the canvas:
sketchpad.clear();
  • change the line thickness:
sketchpad.weight = 20; //in pixels
  • change the color:
sketchpad.color = '#ff485e'; //just like CSS
  • toggle between modes:
sketchpad.mode = 'erase'; // eraser tool
sketchpad.mode = 'fill'; // click to fill area
sketchpad.mode = 'draw'; // default
sketchpad.mode = 'disabled'; // no modification to the canvas (will still fire stroke events)
  • tweak smoothing - higher values make the drawings look much better, lower values make drawing feel a bit more responsive. Set to 0.85 by default.
sketchpad.smoothing = 1.3;
  • toggle adaptive stroke, i.e. line width changing based on drawing speed for a more natural effect. true by default.
sketchpad.adaptiveStroke = false;
  • record stroke data (enables the strokerecorded event). false by default.
sketchpad.recordStrokes = true;
  • export as image:
//we have to get the dataURL of the image
const dataURL = sketchpad.toImage();
//then we can, for instance, open a new window with it
window.open(dataURL);

Events

Dirty/clean

These events fire when the canvas is first drawn on, and when it's cleared. The state is stored in the isDirty property.

sketchpad.addEventListener('dirty', () => console.info(sketchpad.isDirty));
sketchpad.addEventListener('clean', () => console.info(sketchpad.isDirty));

Stroke start/end

These events don't provide any data - they just inform that a stroke has started/finished.

sketchpad.addEventListener('strokestart', () => console.info('strokestart'));
sketchpad.addEventListener('strokeend', () => console.info('strokeend'));

Fill start/end

These only fire in fill mode. The fillstart event also contains x and y properties denoting the starting point of the fill operation (where the user has clicked).

sketchpad.addEventListener('fillstart', ({ x, y }) =>
  console.info(`fillstart ${x} ${y}`),
);
sketchpad.addEventListener('fillend', () => console.info('fillend'));

Stroke recording

strokerecorded fires at the same time as strokeend and contains data necessary for reconstructing the stroke. pointdrawn fires during stroke recording every time the draw method is called. It contains the same data as strokerecorded.

sketchpad.addEventListener('strokerecorded', ({ stroke }) =>
  console.info(stroke),
);
/*
{
  points: [
    {
      point: { x, y },
      time,
    }
  ],
  color,
  weight,
  smoothing,
  adaptiveStroke,
}
*/
sketchpad.addEventListener('pointdrawn', ({ stroke }) =>
  console.info(stroke),
);

Programmatic drawing

To enable functionality such as undo/redo, stroke post-processing, and SVG export in apps using Atrament, the library can be configured to record the "pen strokes".

The first step is to enable recordStrokes, and add a listener for the strokerecorded event:

atrament.recordStrokes = true;
atrament.addEventListener('strokerecorded', ({ stroke }) => {
  // store `stroke` somewhere
});

The stroke can then be reconstructed using methods of the Atrament class:

// set drawing options
atrament.mode = stroke.mode;
atrament.weight = stroke.weight;
atrament.smoothing = stroke.smoothing;
atrament.color = stroke.color;
atrament.adaptiveStroke = stroke.adaptiveStroke;

// don't want to modify original data
const points = stroke.points.slice();

const firstPoint = points.shift().point;
// beginStroke moves the "pen" to the given position and starts the path
atrament.beginStroke(firstPoint.x, firstPoint.y);

let prevPoint = firstPoint;
while (points.length > 0) {
  const point = points.shift().point;

  // the `draw` method accepts the current real coordinates
  // (i. e. actual cursor position), and the previous processed (filtered)
  // position. It returns an object with the current processed position.
  const { x, y } = atrament.draw(point.x, point.y, prevPoint.x, prevPoint.y);

  // the processed position is the one where the line is actually drawn to
  // so we have to store it and pass it to `draw` in the next step
  prevPoint = { x, y };
}

// endStroke closes the path
atrament.endStroke(prevPoint.x, prevPoint.y);

Development

To obtain the dependencies, cd into the atrament directory and run npm install. You should be able to then build atrament by simply running npm run build.

I didn't bother writing tests because it's such a small package. Contributions are welcome!

More Repositories

1

graphql-json-schema

Converts from GraphQL Schema Language to JSON Schema
JavaScript
29
star
2

panner-utils

Utility functions to calculate vector values for the Web Audio PannerNode
JavaScript
12
star
3

alluvial-sharawadji

distributed soundwalks
JavaScript
5
star
4

sverchok-nodes

A collection of custom scripted nodes for the Blender Sverchok plugin
Python
5
star
5

1wall

A collaborative drawing platform on the Web.
JavaScript
3
star
6

minimaltune

Lightweight, but very accurate guitar tuner for OSX
Processing
3
star
7

meyda-presentation

Presentation of Meyda for WAC and others
JavaScript
3
star
8

instaphun

Code for my custom Instagram AR filters. Very experimental.
JavaScript
2
star
9

panner-examples

Nice isolated examples of using various features of the Web Audio PannerNode
JavaScript
2
star
10

jakubs-max-abs

Jakub's Max/MSP Abstractions and Externals
Max
2
star
11

cloudwatch-logger

Asynchronous logs from node.js to AWS CloudWatch Logs
JavaScript
2
star
12

wtfmate

Fun with the Speech Synthesis API.
HTML
2
star
13

Sampluino

A sampler keyboard instrument built with an Arduino UNO
Arduino
2
star
14

aavp

portfolio of projects for the Advanced Audiovisual Processing course at Goldsmiths
CSS
2
star
15

ripple

A ripple-effect music sequencer
C
2
star
16

iplayer-az

iPlayer A to Z listing for BBC Web Dev application
JavaScript
1
star
17

anthropoid

all kinds of code for my personal home Pi
HTML
1
star
18

minimalwave

a lightweight sketch-the-waveform synth
C++
1
star
19

sl-glove-docs

Documentation and other materials for the Sign Language Glove
1
star
20

ECO-reader

openFrameworks implementation of structured light scanning for Ex Caelis Oblata excaelisoblata.tumblr.com
C
1
star
21

lex

Website for Light Experiments by Jasmin Michalcakova and myself
JavaScript
1
star
22

alchemical-marriage

Visuals for The Alchemical Marriage
1
star
23

nozomu-printer

Shell
1
star
24

sl-glove-engine

A python engine for gesture classification, interfacing with IBM Watson and the SLG web app
1
star
25

martyr

attracts evil over HTTP
1
star
26

extinction

Some visual experiments with the Extinction Symbol
JavaScript
1
star
27

sl-glove-app

A socket.io-based app for the Sign Language Glove project at Global AI Hackathon Seoul
JavaScript
1
star
28

worlds

weird webgl sketches, environments and compositions that i do when nothing else makes sense
JavaScript
1
star
29

uc-map

The United Cassettes Map
PHP
1
star
30

embracing-change

A braindump of thoughts and resources about embracing change by design in software and art
1
star