Created
October 14, 2012 13:09
-
-
Save tos-kamiya/3888518 to your computer and use it in GitHub Desktop.
HTML5 Canvas Drawing of Pentagram, Heptagram, ...
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"> | |
<title>n-tagram</title> | |
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> | |
</head> | |
<body> | |
<label for="pointsSpinner">Points: </label> | |
<input id="pointsSpinner" type="number" value="5"/> | |
<label for="stepSpinner">Step: </label> | |
<input id="stepSpinner" type="number" value="2"/> | |
<canvas id="thecanvas" width="600" height="600"></canvas> | |
<script type="text/javascript"> | |
var $cvs = null; | |
var $ctx = null; | |
var $R = null; | |
var update_context = (function() { | |
$cvs = $("#thecanvas")[0]; | |
$ctx = $cvs.getContext("2d"); | |
var width = $cvs.width; | |
var height = $cvs.height; | |
$R = (width < height ? width : height) / 2; | |
}); | |
var clear = (function() { | |
update_context(); | |
$ctx.fillStyle = "rgb(255,255,255)"; | |
$ctx.fillRect(0, 0, $cvs.width, $cvs.height); | |
}); | |
var ntagram = (function(points, step, color) { | |
update_context(); | |
$ctx.strokeStyle = color; | |
$ctx.lineWidth = 5; | |
$ctx.lineCap = "round"; | |
for(var i = 0; i < points; ++i) { | |
var t = 2 * Math.PI * (i * step) / points; | |
var x = $R + $R * Math.cos(t); | |
var y = $R + $R * Math.sin(t); | |
$ctx.beginPath(); | |
$ctx.moveTo(x, y); | |
t = 2 * Math.PI * ((i + 1) * step) / points; | |
x = $R + $R * Math.cos(t); | |
y = $R + $R * Math.sin(t); | |
$ctx.lineTo(x, y); | |
$ctx.stroke(); | |
} | |
}); | |
</script> | |
<script type="text/javascript"> | |
$(function() { | |
// set-up event handlers | |
var pointsSpinner = $("#pointsSpinner")[0]; | |
var stepSpinner = $("#stepSpinner")[0]; | |
var redraw = (function() { | |
clear(); | |
ntagram(pointsSpinner.value, 1, "red"); | |
ntagram(pointsSpinner.value, stepSpinner.value, "blue"); | |
}); | |
pointsSpinner.addEventListener("input", redraw, false); | |
stepSpinner.addEventListener("input", redraw, false); | |
// fire initial drawing | |
redraw(); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Chrome/chromium (or any HTML5-supporting browsers) recommend, because the numbers of "Points" and "Step" can be modified with cursor keys.