cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - Activehtmlicon-personicon-teamoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External CSS

These stylesheets will be added in this order and before the code you write in the CSS editor. You can also add another Pen here, and it will pull the CSS from it. Try typing "font" or "ribbon" below.

Quick-add: + add another resource

Add External JavaScript

These scripts will run in this order and before the code in the JavaScript editor. You can also link to another Pen here, and it will run the JavaScript from it. Also try typing the name of any popular library.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <header>
	<h1>New York City</h1>
	<h2>Congressional District Map</h2>
	<p><i>Using TopoJSON data @ ~12kb</i></p>
</header>
<div id="wrapper">
	<canvas width="800" height="350" id="map-canvas"></canvas>
</div>
            
          
!
            
              * {
	padding: 0;
	margin: 0;
	outline: 0;
	border: 0;
}

header {
	position: absolute;
	font-family: sans-serif;
	font-weight: 100;
	padding: 15px 20px;
	color: #444;
}

h1, h2{
	font-weight: 600;
}

h2 {
	color: #bd6332;
	margin: 4px 0 8px;
	font-weight: 300;
}

#wrapper {
	display: flex;
	display: -webkit-flex;
	display: -moz-flex;
	display: -ms-flex;
	justify-content: center;
	-webkit-justify-content: center;
	-moz-justify-content: center;
	-ms-justify-content: center;
	align-items: center;
	-webkit-align-items: center;
	-moz-align-items: center;
	-ms-align-items: center;
	width: 100%;
	width: calc( 100% - 8px);
	height: 100%;
	height: calc( 100% - 8px);
	position: absolute;
}
            
          
!
            
              // Mapping TopoJSON data:
// Imports json data, decodes, projects and renders to a canvas stage
// XHR import call has been removed from the code in favor of importing a codepen storing the topoJSON data
// certain redundant variables have been reomved as a result
(function() {
	"use strict";
	// stores converted topojson to geojson format
	var geojson,
		// look-up key to access topojson features
		topologyKey = "nyc_congress_districts",
		// dictionary of rendering options
		renderOptions = {
			padding: 50,
			fillColor: "#f8c59d",
			strokeColor: "#bd6332",
			strokeWidth: 1
		},
		// reference to our map canvas
		canvas = document.getElementById("map-canvas");

	// create HD canvas based on pixelDeviceRatio
	createHDCanvas(canvas);

	// IIFE to begin topoJSON conversion, projection and rendering
	(function() {
		// convert topology to geojson format using topojson API
		geojson = topojson.feature(
			topology,
			topology.objects[topologyKey]);
		// project coordinates to canvas bounds
		mapCoordinatesToCanvas(
			canvas,
			geojson);
		// render GeoJSON
		renderGeoJSONTo(canvas, geojson);
	}());

	// iterate through all positions within the topology
	// determine the extreme most positions of both lat and long
	// returns the range in object literal form 
	function findGeographicBounds(featureCollection) {
		var range = {};
		featureCollection.features.forEach(
			function(feature) {
				iterateFeaturePolygons(
					feature,
					findExtremesIn);
			});
		return range;
		// algorithm to determine range of all geometry positions in the featureCollection
		function findExtremesIn(polygon) {
			polygon.map(
				function(position) {
					if (range.x && range.y) {
						range.x.max = position[0] > range.x.max ?
							position[0] :
							range.x.max;
						range.x.min = position[0] < range.x.min ?
							position[0] :
							range.x.min;
						range.y.max = position[1] > range.y.max ?
							position[1] :
							range.y.max;
						range.y.min = position[1] < range.y.min ?
							position[1] :
							range.y.min;
					} else {
						range.x = {};
						range.y = {};
						range.x.max = range.x.min = position[0];
						range.y.max = range.y.min = position[1];
					}
				});
		}
	}

	// helper function to apply a callback to each polygon within a feature's geometry
	function iterateFeaturePolygons(feature, callback) {
		switch (feature.geometry.type) {
			case "MultiPolygon":
				feature.geometry.coordinates.forEach(
					function(polygons) {
						polygons.map(callback);
					});
				break;
			case "Polygon":
				feature.geometry.coordinates.map(callback);
		}
	}

	// with a canvas node and topology reference
	// map the transformation data to each position
	function mapCoordinatesToCanvas(canvas, featureCollection) {
		// grab reference to canvas dimensions
		var canvasBounds = canvas.getBoundingClientRect(),
			// collect extreme bounding points in the featureCollection
			geoBounds = findGeographicBounds(featureCollection),
			// calculate ranges from max - min
			rangeX = geoBounds.x.max - geoBounds.x.min,
			rangeY = geoBounds.y.max - geoBounds.y.min,
			// calculate ratio of ranges to bounding dimensions
			ratioX = rangeX / (canvasBounds.width - renderOptions.padding) / canvas.ratio,
			ratioY = rangeY / (canvasBounds.height - renderOptions.padding) / canvas.ratio,
			// determine greater ratio to scale map coordinates to
			greaterRatio = ratioX > ratioY ?
			ratioX :
			ratioY,
			// determine axial centering offsets
			centerX = (canvas.width - rangeX / greaterRatio) / 2,
			centerY = (canvas.height - rangeY / greaterRatio) / 2;
		// iterate through all features
		featureCollection.features.forEach(
			function(feature) {
				// itrate through positions and apply transformation
				iterateFeaturePolygons(
					feature,
					transformPositionsIn);
			});
		// coordinate transformation algorithm
		function transformPositionsIn(polygon) {
			polygon.map(
				function(position) {
					position[0] = (position[0] - geoBounds.x.min) / rangeX * (rangeX / greaterRatio) + centerX;
					position[1] = (1 - (position[1] - geoBounds.y.min) / rangeY) * (rangeY / greaterRatio) + centerY;
				});
		}
	}

	// iterates through features of geoJSON and draws each feature to the specified stage
	function renderGeoJSONTo(canvas, geojson) {
		geojson.features.forEach(
			function(feature) {
				drawFeatureToCanvas(
					canvas,
					feature);
			});
	}

	// a method to draw a feature to an HTML canvas
	function drawFeatureToCanvas(canvas, feature) {
		// grab context reference and set context styling
		var context = canvas.getContext("2d");
		context.fillStyle = renderOptions.fillColor;
		context.strokeStyle = renderOptions.strokeColor;
		context.lineWidth = renderOptions.strokeWidth * canvas.ratio;
		// grab polys and render them individually
		iterateFeaturePolygons(
			feature,
			renderPoly);
		// builds 2d path for canvas
		function renderPoly(poly) {
			context.beginPath();
			poly.forEach(
				function(position, index) {
					if (index) {
						context.lineTo(
							position[0],
							position[1]);
					} else {
						context.moveTo(
							position[0],
							position[1]);
					}
				});
			context.fill();
			context.stroke();
			context.closePath();
		}
	}

	// ensures a canvas displays at an optimal resolution given
	// the end user device's display technology as reported by browser
	// helpful for retina/mobile display fidelity
	function createHDCanvas(canvas) {
		// determine the device's pixel ratio
		canvas.ratio = window.devicePixelRatio || 1;
		// preserve the style width/height
		canvas.style.width = canvas.width + "px";
		canvas.style.height = canvas.height + "px";
		// update the underlying canvas dimensions
		canvas.width *= canvas.ratio;
		canvas.height *= canvas.ratio;
	}
}());
            
          
!
999px
Close

Asset uploading is a PRO feature.

As a PRO member, you can drag-and-drop upload files here to use as resources. Images, Libraries, JSON data... anything you want. You can even edit them anytime, like any other code on CodePen.

Go PRO

Loading ..................

Console