Created
July 11, 2018 08:05
-
-
Save dashawk/77a41d784cb862a59b7a3c5494f9cc00 to your computer and use it in GitHub Desktop.
This file contains 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
var canvas = document.getElementById('canvas'); | |
var ctx = canvas.getContext("2d"); | |
var myPoints = [ | |
[37.772,-122.214], | |
[21.291, -157.821], | |
[-18.142, 178.431], | |
[-27.467, 153.027] | |
] | |
var minX, minY, maxX, maxY; | |
myPoints.forEach((p, i) => { | |
if (i === 0) { // if first point | |
minX = maxX = p[0]; | |
minY = maxY = p[1]; | |
} else { | |
minX = Math.min(p[0], minX); | |
minY = Math.min(p[1], minY); | |
maxX = Math.max(p[0], maxX); | |
maxY = Math.max(p[1], maxY); | |
} | |
}); | |
// now get the map width and heigth in its local coords | |
const mapWidth = maxX - minX; | |
const mapHeight = maxY - minY; | |
const mapCenterX = (maxX + minX) / 2; | |
const mapCenterY = (maxY + minY) / 2; | |
// to find the scale that will fit the canvas get the min scale to fit height or width | |
const scale = Math.min(canvas.width / mapWidth, canvas.height / mapHeight); | |
// Now you can draw the map centered on the cavas | |
ctx.beginPath(); | |
myPoints.forEach(p => { | |
ctx.lineTo( | |
(p[0] - mapCenterX) * scale + canvas.width / 2, | |
(p[1] - mapCenterY) * scale + canvas.height / 2 | |
); | |
}); | |
ctx.stroke(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment