css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <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
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console