Created
July 24, 2021 09:38
-
-
Save likev/80e0286d973a0335c6dd137741c7baf4 to your computer and use it in GitHub Desktop.
smoothPolygon use turf // source https://jsbin.com/hapemesege
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>smoothPolygon use turf</title> | |
<style> | |
canvas{ | |
margin:20px; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id='canvas' width=800 height=600></canvas> | |
<script src='https://unpkg.com/@turf/turf@6/turf.min.js'></script> | |
<script> | |
function drawPoints(points) { | |
const canvas = document.getElementById('canvas'); | |
const ctx = canvas.getContext('2d'); | |
ctx.save(); | |
ctx.translate(100, 100) | |
const start = points[0]; | |
ctx.beginPath(); // Start a new path | |
ctx.moveTo(start[0], start[1]); // Move the pen to (30, 50) | |
for (let i = 1; i < points.length; i++) { | |
const point = points[i]; | |
ctx.lineTo(point[0], point[1]); // Draw a line to (150, 100) | |
} | |
ctx.stroke(); // Render the path | |
ctx.restore(); | |
} | |
</script> | |
<script> | |
function smoothPolygon(pg, extend) { | |
let result = [], | |
line = [], | |
start = false, | |
edge = false, | |
index = 0; | |
let [minX, minY] = extend[0], [maxX, maxY] = extend[1]; | |
for (let point of pg) { | |
if (point[0] <= minX || point[0] >= maxX || point[1] <= minY || point[1] >= maxY) { | |
edge = true; | |
} else { | |
line.push(point) | |
edge = false; | |
} | |
if (start) { | |
if (index === pg.length - 1 || edge) { | |
console.log(line) | |
var linef = turf.lineString(line); | |
var curved = turf.bezierSpline(linef, { | |
resolution: 10000, | |
sharpness: 0.95 | |
}); | |
result = result.concat(curved.geometry.coordinates) | |
line = []; | |
start = false; | |
} | |
} else { | |
if (!edge) start = true; | |
} | |
if(edge) result.push(point); | |
index++ | |
} | |
return result; | |
} | |
var linetest = [ | |
[0, 0], | |
[20, 30], | |
[40, 40], | |
[60, 30],[80, 10], | |
[100, 0], | |
[100, 100], | |
[0, 100], | |
[0, 0] | |
]; | |
drawPoints(linetest) | |
drawPoints(smoothPolygon(linetest, [[0,0],[100,100]])) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment