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);
console.log("followpath");
var path = followPath(startPixel, dat, 0 );
console.log("draw");
path.draw(context);
console.log("end");
function Path(sp) {
this.startpixel = sp;
this.lastpixel = { x: -1, y: -1};
this.map = new Array();
}
Path.prototype.closed = function(pixel) {
return (this.startpixel.x == this.lastpixel.x && this.startpixel.y == this.lastpixel.y);
}
Path.prototype.left = function(pixel) {
this.lastpixel = pixel;
this.map.push(pixel);
return this;
}
Path.prototype.right = function(pixel) {
this.lastpixel = pixel;
this.map.push(pixel);
return this;
}
Path.prototype.up = function(pixel) {
this.lastpixel = pixel;
this.map.push(pixel);
return this;
}
Path.prototype.down = function(pixel) {
this.lastpixel = pixel;
this.map.push(pixel);
return this;
}
Path.prototype.draw = function(context) {
context.save();
context.moveTo(this.startpixel.x, this.startpixel.y);
var map = properRDP(this.map, 4);
console.log("original: " + this.map.length);
console.log("RDP: " + map.length);
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=i;
}
}
if (dist>epsilon){
// iterate
var l1=points.slice(0, index+1);
...