Pen Settings

HTML

CSS

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

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <figure id='earth'>
	<details class='color ocean-fill-1'></details>
	<details class='color ocean-fill-2'></details>
	<details class='color land-fill'></details>
	<details class='color land-stroke'></details>
	<details class='color country-border'></details>
	<details class='color country-selected'></details>
	<details class='color globe-grid'></details>
	<details class='color globe-outline'></details>
</figure>
<div id='controls'>
	<p id='info'>Info</p>
</div>
              
            
!

CSS

              
                // Globals
$cOceanFill1: rgb(16,64,255);
$cOceanFill2: rgb(8,32,128);
$cLandFill: rgba(64,128,255,.25);
$cLandStroke: rgba(255,255,255,.5);
$cCountryBorder: rgba(255,255,255,.5);
$cCountrySelected: rgba(0,240,0,.5);
$cGlobeGrid: rgba(255,255,255,.25);
$cGlobeOutline: rgb(64,128,255);

*, *:before, *:after {
	box-sizing: border-box;
}
html, body {
	width: 100%;
	height: 100%;
	margin: 0;
}
#earth {
	width: 100%;
	height: 100%;
	margin: 0;
	background: black;
	.color { display: none; // Colours reused in script
		&.ocean-fill-1 { color: $cOceanFill1; }
		&.ocean-fill-2 { color: $cOceanFill2; }
		&.land-fill { color: $cLandFill; }
		&.land-stroke { color: $cLandStroke; }
		&.country-border { color: $cCountryBorder; }
		&.country-selected { color: $cCountrySelected; }
		&.globe-grid { color: $cGlobeGrid; }
		&.globe-outline { color: $cGlobeOutline; }
	}
}
#controls {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	padding: .5em;
	color: #ddd;
	background: rgba(48,48,48,.75);
	opacity: .5;
	&:hover {
		opacity: 1;
	}
}
              
            
!

JS

              
                if (world_110m) { //loading resource from other Pen
	var world = world_110m;
} else {
	console.log("No topo data loaded!"); 
}
if (world_country_names) { //loading resource from other Pen
	var names = world_country_names;
} else {
	console.log("No country data loaded!"); 
}

var win = d3.select( window ),
	container = d3.select( "#earth" ),
	
	width = parseInt(container.style( "width" )),
	height = parseInt(container.style( "height" )),
	whMin = width < height ? width : height,
	center = [width / 2, height / 2],
	scale = (whMin / 2) * 0.9, // - margin * 2, // initial scale
	scaleExt = [100, 3000],
	
	canvas = container.append( "canvas" )
		.attr( "width", width )
		.attr( "height", height ),
    ctx = canvas.node().getContext( "2d" ),
	img_canvas = d3.select( document.createElement( 'canvas' ) )
		.attr( "width", width )
		.attr( "height", height ),
	img_ctx = canvas.node().getContext( "2d" ),
	
	projection = d3.geo.orthographic()
		.clipAngle( 90 )
    	.translate( center )
    	.scale( scale )
    	.precision(0.5),
	path = d3.geo.path()
    	.projection( projection )
    	.context( ctx ),
	graticule = d3.geo.graticule()
		.extent( [[-180, -90], [180 - .1, 90 - .1]] ),
	startLon = 0, startLat = -51, startZoom,
	endLon, endLat, endZoom,
	
	d3_img = function( src, cb ) {
    	var img = new Image();
    	img.src = "http://www.lenart.pl/assets/codepen/world-texture.jpg"; //= src
    	img.onload  = function() { cb( null, img ); };
    	img.onerror = function() { cb( 'Error', null ); };
	},
	
	cOceanFill1 = getColor( '.color.ocean-fill-1' ),
	cOceanFill2 = getColor( '.color.ocean-fill-2' ),
	cLandFill = getColor( '.color.land-fill' ),
	cLandStroke = getColor( '.color.land-stroke' ),
	cCountryBorder = getColor( '.color.country-border' ),
	cCountrySelected = getColor( '.color.country-selected' ),
	cGlobeGrid = getColor( '.color.globe-grid' ),
	cGlobeOutline = getColor( '.color.globe-outline' );
		
//

var texture = d3_img;

window.projection = projection;

//d3.queue()
//	.defer( d3.json, "http://www.lenart.pl/assets/codepen/world-110m.json" )
//	.defer( d3.tsv, "http://www.lenart.pl/assets/codepen/world-country-names.tsv" )
//	.defer( d3_img, "http://www.lenart.pl/assets/codepen/world-texture.jpg")
//	.await( ready );

//function ready( error, world, names, texture ) {
//	if ( error ) throw error;

	var zoom = d3.geo.zoom()
		.projection( projection )
		.scaleExtent( scaleExt )
		.on( "zoom", function() {
			drawEarth();
		})
		.on("zoomend", function() {
			updateControls();
		}),
	
		globe = {type: "Sphere"},
		land = topojson.feature( world, world.objects.land ),
		countries = topojson.feature( world, world.objects.countries ).features,
		borders = topojson.mesh( world, world.objects.countries, function(a, b) { return a !== b }),
		grid = graticule(),
		c = -1,
		n = countries.length,
		tw = texture.width,
		th = texture.height;

	countries = countries.filter(function(d) {
		return names.some(function(n) {
			if ( d.id == n.id ) return d.name = n.name;
		});
	}).sort(function(a, b) {
		return a.name.localeCompare( b.name );
	});
	
	// user coords?
	// https://www.w3schools.com/html/html5_geolocation.asp
	// animate to initial position?
	drawEarth();
	
	/*
	
	*/
	
	//  Events
	
	//canvas.transition().ease("quad-in-out").duration(2e3).call( projection.rotate([0,-51,0]) );
	
	canvas
		.call( zoom )
		.on( 'dblclick.zoom', function() { // null 
			// zoom to country's bbox
			console.log( 'mouse: ' + projection.invert( d3.mouse( this ) ) );
		});
	
	win
		.on( 'resize', windowResized );
	
	//
	
	function windowResized() {
		width = parseInt( container.style( "width" ) );
		height = parseInt( container.style( "height" ) );
		canvas
			.attr( "width", width )
			.attr( "height", height );
		whMin = width < height ? width : height;
		center = [width / 2, height / 2];
		projection
			//.scale( whMin / 2 ... ) // interpolate old->new
			.translate( center );
		
		drawEarth();
		
	}
	
	function drawEarth() {
		
		var dia = projection.scale();
		
		ctx.clearRect( 0, 0, width, height );
		
		// Texture reprojection
		// https://bl.ocks.org/mbostock/4329423
		// https://github.com/metocean/d3-geo-raster
		// drawTexture();
		
		// Oceans
		var grad = ctx.createRadialGradient( 
			center[0] - dia / 2, center[1] - dia / 2, 0, 
			center[0] - dia / 2, center[1] - dia / 2, dia * 1.5 
		);
		grad.addColorStop( 0, cOceanFill1 );
		grad.addColorStop( 1, cOceanFill2 );
		ctx.fillStyle = grad,
		ctx.beginPath(), 
		path( globe ), 
		ctx.fill();

		// Land
		ctx.fillStyle = cLandFill,
		ctx.strokeStyle = cLandStroke,
		ctx.lineWidth = .75,
		ctx.beginPath(), 
		path( land ), 
		ctx.fill(),
		ctx.stroke();

		// Selected country
		ctx.fillStyle = cCountrySelected,
		ctx.beginPath(), 
		path( countries[c] ),
		ctx.fill();

		// Country borders
		ctx.strokeStyle = cCountryBorder,
		ctx.lineWidth = .5, 
		ctx.beginPath(), 
		path( borders ), 
		ctx.stroke();

		// Globe grid
		ctx.strokeStyle = cGlobeGrid,
		ctx.lineWidth = .5,
		ctx.beginPath(),
		path( grid ),
		ctx.stroke();

		// Globe outline
		ctx.strokeStyle = cGlobeOutline, 
		ctx.lineWidth = 1, 
		ctx.beginPath(), 
		path( globe ), 
		ctx.stroke();
		
		// Cross at centre
		drawCross( width / 2, height / 2 );
	}
	
	function drawTexture() {
		
		img_ctx.drawImage( texture, 0, 0, tw, th );

		var sourceData = img_ctx.getImageData( 0, 0, tw, th ).data,
			target = img_ctx.createImageData( width, height ),
			targetData = target.data;

		for (var y = 0, i = -1; y < height; ++y) {
			for (var x = 0; x < width; ++x) {
				var p = projection.invert([x, y]), λ = p[0], φ = p[1];
				if (λ > 180 || λ < -180 || φ > 90 || φ < -90) { i += 4; continue; }
				var q = ((90 - φ) / 180 * th | 0) * tw + ((180 + λ) / 360 * tw | 0) << 2;
				targetData[++i] = sourceData[q];
				targetData[++i] = sourceData[++q];
				targetData[++i] = sourceData[++q];
				targetData[++i] = 255;
			}
		}

		//context.clearRect(0, 0, width, height);
		img_ctx.putImageData(target, 0, 0);
	}
	
	function drawCross( x, y ) {
		ctx.strokeStyle = "rgba(255,255,255,.5)";
		ctx.lineWidth = 1;
		ctx.setLineDash( [20] );
		ctx.beginPath();
		ctx.moveTo( x - 30, y );
		ctx.lineTo( x + 30, y );
		ctx.stroke();
		ctx.beginPath();
		ctx.moveTo( x, y - 30 );
		ctx.lineTo( x, y + 30 );
		ctx.stroke();
		ctx.setLineDash([]);
	}
	
	function updateControls() {
		
		// get country name
		// update lon, lat, zoom, country
		var pr = projection.rotate();
		var cc = typeof findCountry( pr[0], pr[1] ) !== 'undefined' ?  cc : { id: -1, name: '' };
		
		console.log( 'country ' + cc.id + ': ' + cc.name );

		console.log(
			'lonlat: ' + pr[0] + ', ' + pr[1] + ', ' +
			// 'xy: ' + projection.invert(pr) + ', ' +
			'scale: ' + projection.scale()
		);
		
	}
	
	function findCountry( lon, lat ) {
		
		var point = [ lat, -lon ],
			j = 0,
			country,
			polygon,
			polygons;
		
		while ( j < countries.length ) {
			
			country = countries[j];
			
			if ( country.geometry.type === 'Polygon' ) {
				
				polygon = country.geometry.coordinates[0];
			
				if ( d3.polygonContains( polygon, point ) ) {
					
					return { id: j, name: country.name };
					break;
					
				} else if (country.geometry.type === 'MultiPolygon') {
					
					polygons = country.geometry.coordinates;
					
					for ( var jj = 0; jj < polygons.length; jj++ ) {
						
						if ( d3.polygonContains( polygons[jj][0], point ) ) {
					
							return { id: j, name: country.name };
							break;
					
						}
						
					}
					
				}
				
			}
			
			j++;
			
		}
		
	}

	
	
//}

function getColor( el, col ) {
	
	var col = typeof col !== 'undefined' ?  col : '#888';
	return d3.select( el ).empty() ? col : d3.select( el ).style( 'color' );
	
}
              
            
!
999px

Console