Use Geometric.js to scale a polygon.
Last active
February 10, 2019 19:19
-
-
Save HarryStevens/a1287efa722f7e681dd0b8e8c9e616c9 to your computer and use it in GitHub Desktop.
Scale a Polygon
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
license: gpl-3.0 |
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> | |
<style> | |
body { | |
margin: 0; | |
font-family: "Helvetica Neue", sans-serif; | |
} | |
.input-wrapper { | |
padding: 10px; | |
position: absolute; | |
} | |
polygon { | |
fill: steelblue; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="input-wrapper"> | |
<div> | |
Size: <span class="scale-factor">100%</span> | |
</div> | |
<input type="range" min="10" max="200" value="100" /> | |
</div> | |
<script src="https://d3js.org/d3.v5.min.js"></script> | |
<script src="https://unpkg.com/[email protected]/build/geometric.min.js"></script> | |
<script> | |
var width = window.innerWidth, | |
height = window.innerHeight, | |
center = [width / 2, height / 2], | |
vertices = [ | |
[center[0] - 100, center[1] - 100], | |
[center[0], center[1] - 130], | |
[center[0] + 100, center[1] - 100], | |
[center[0] + 150, center[1]], | |
[center[0] + 100, center[1] + 100], | |
[center[0], center[1] + 130], | |
[center[0] - 100, center[1] + 100], | |
[center[0] - 150, center[1]] | |
]; | |
var input = d3.select("input"); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
var polygon = svg.append("polygon") | |
.attr("points", vertices.join(" ")); | |
input.on("input", _ => { | |
var scaleFactor = +input.property("value") / 100; | |
var newVertices = geometric.polygonScale(vertices, scaleFactor); | |
polygon.attr("points", newVertices.join(" ")); | |
d3.select(".scale-factor").text(Math.round(scaleFactor * 100) + "%"); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment