JSFiddle - React, Tailwind, and code Playground
by sirhc
HTML
<script src="https://github.com/paperjs/paper.js/raw/master/dist/paper.js"></script>
<textarea id="theJSON"></textarea>
Draw below:
<canvas id="myCanvas" resize></canvas>
CSS
#theJSON { width: 100%; height: 100px }
JavaScript
paper.install(window);
// Get a reference to the canvas object
var canvas = document.getElementById('myCanvas');
// Create an empty project and a view for the canvas:
paper.setup(canvas);
var path;
// Create a Paper.js Path to draw a line into it:
var textItem = new PointText(new Point(20, 55));
textItem.fillColor = 'black';
textItem.content = 'Click and drag to draw a line.';
var tool = new Tool();
tool.onMouseDown = function(event) {
// If we produced a path before, deselect it:
if (path) {
path.selected = false;
}
// Create a new path and set its stroke color to black:
path = new Path();
path.add(event.point);
path.strokeColor = 'black';
// Select the path, so we can see its segment points:
path.fullySelected = true;
view.draw(path);
}
tool.onMouseDrag = function(event) {
path.add(event.point);
// Update the content of the text item to show how many
// segments it has:
textItem.content = 'Segment count: ' + path.segments.length;
}
tool.onMouseUp = function(event) {
var segmentCount = path.segments.length;
// When the mouse is released, simplify it:
path.simplify(10);
// Select the path, so we can see its segments:
path.fullySelected = true;
var newSegmentCount = path.segments.length;
var difference = segmentCount - newSegmentCount;
var percentage = 100 - Math.round(newSegmentCount / segmentCount * 100);
textItem.content = difference + ' of the ' + segmentCount + ' segments were removed. Saving ' + percentage + '%';
$("#theJSON").val(path.segments);
}