Created
October 30, 2020 18:15
-
-
Save jm42/cbbbdc6e2afcbca8b6d17eee0b8586e2 to your computer and use it in GitHub Desktop.
Draw an SVG compass
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 lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Compass</title> | |
</head> | |
<body> | |
<svg id="compass" width="220" height="220" viewBox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> | |
<circle cx="110" cy="110" r="108" fill="none" stroke="#321" stroke-width="2" /> | |
<polygon points="88,110 110,55 132,110" fill="#321" stroke="#321" stroke-width="2" /> | |
<polygon points="88,110 110,165 132,110" fill="none" stroke="#321" stroke-width="2" /> | |
</svg> | |
<script> | |
document.addEventListener('DOMContentLoaded', function() { | |
var svgns = "http://www.w3.org/2000/svg"; | |
var compass = document.getElementById('compass'); | |
var cx = 110; | |
var cy = 110; | |
var r = 108; | |
var i; | |
for (i = 0; i < 360; i++) { | |
if (i % 45 !== 0 && i % 5 !== 0) { | |
continue; | |
} | |
var l = i % 45 === 0 ? 40 : 20; | |
var rx1 = (r - l) * Math.cos(i * Math.PI / 180); | |
var ry1 = (r - l) * Math.sin(i * Math.PI / 180); | |
var rx2 = r * Math.cos(i * Math.PI / 180); | |
var ry2 = r * Math.sin(i * Math.PI / 180); | |
var line = document.createElementNS(svgns, 'line'); | |
line.setAttribute('x1', cx + rx1); | |
line.setAttribute('y1', cy + ry1); | |
line.setAttribute('x2', cx + rx2); | |
line.setAttribute('y2', cy + ry2); | |
line.setAttribute('stroke', '#321'); | |
line.setAttribute('stroke-width', '1'); | |
compass.appendChild(line); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment