JSFiddle - React, Tailwind, and code Playground
by Emanuel Vecchio
HTML
<canvas id="canvas" width="800" height="600"></canvas>
<img alt="" id="img" style="visibility: hidden"...
JavaScript
var dat = {};
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var img = document.getElementById("img");
dat.width = img.width;
dat.height = img.height;
context.drawImage(img, 0, 0);
dat = context.getImageData(0, 0, dat.width, dat.height);
var startPixel = findStartPixel(dat, 0);
var path = followPath(startPixel, dat, 0);
draw(path.map);
var shortmap = properRDP(this.map, 4);
console.log("original: " + path.map.length);
console.log("RDP: " + sortmap.length);
function Path(sp) {
this.startpixel = sp;
this.lastpixel = {
x: -1,
y: -1
};
this.map = new Array();
this.closed = function (pixel) {
return (this.startpixel.x == this.lastpixel.x && this.startpixel.y == this.lastpixel.y);
}
this.left = function (pixel) {
this.lastpixel = pixel;
this.map.push(pixel);
return this;
}
this.right = function (pixel) {
this.lastpixel = pixel;
this.map.push(pixel);
return this;
}
this.up = function (pixel) {
this.lastpixel = pixel;
this.map.push(pixel);
return this;
}
this.down = function (pixel) {
this.lastpixel = pixel;
this.map.push(pixel);
return this;
}
}
function draw(context, map) {
context.save();
context.moveTo(this.startpixel.x, this.startpixel.y);
for (var i = 0; i < map.length; i++) {
var p = map[i];
context.lineTo(p.x, p.y);
}
context.strokeStyle = 'red';
context.stroke();
context.restore();
}
function properRDP(points, epsilon) {
var firstPoint = points[0];
var lastPoint = points[points.length - 1];
if (points.length < 3) {
return points;
}
var index = -1;
var dist = 0;
for (var i = 1; i < points.length - 1; i++) {
var cDist = findPerpendicularDistance(points[i], firstPoint, lastPoint);
if (cDist > dist) {
dist = cDist;
index...