D3 Test

In this example below you will see how to do a D3 Test with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by 1cco, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright 1cco ©
  • HTML
  • CSS
  • JavaScript
    

/*Downloaded from https://www.codeseek.co/1cco/d3-test-jKMpXV */
    


/*Downloaded from https://www.codeseek.co/1cco/d3-test-jKMpXV */
    //Width and height
var w = 500;
var h = 300;
// var dataset = [
// 	[5, 20], [480, 90], [250, 50], [100, 33], [330, 95],
// 	[410, 12], [475, 44], [25, 67], [85, 21], [220, 88]
// ];
// for (var i = 0; i < 10; i++) {
// 	dataset.push([Math.floor(Math.random() * w), Math.floor(Math.random() * h)]);
// }
var randomX = d3.randomNormal(w / 2, 80),
    randomY = d3.randomNormal(h / 2, 80),
    dataset = d3.range(10)
		.map(function() { return [randomX(), randomY()]; });
//Create scale functions
// var xScale = d3.scaleLinear()
// 	.domain([0, d3.max(dataset, function(d) { return d[0]; })])
// 	.range([0, w]);
// var yScale = d3.scaleLinear()
// 	.domain([0, d3.max(dataset, function(d) { return d[1]; })])
// 	.range([h, 0]);
// //Create SVG element
var svg = d3.select("body")
	.append("svg")
	.attr("width", w)
	.attr("height", h);

var circle = svg.selectAll("circle")
	.data(dataset)
	.enter()
	.append("circle")
	//  .attr("cx", function(d) {
	// 	return xScale(d[0]);
	//  })
	// .attr("cy", function(d) {
	// 	return yScale(d[1]);
	// })
	.attr("r", function(d) {
		// return Math.sqrt(h - d[1]);
		return 5;
	})
	.attr("fill", "#ccc")
	.attr("transform", transform(d3.zoomIdentity));

var text = svg.selectAll("text")
	.data(dataset)
	.enter()
	.append("text")
	.text(function(d, i){
		return i;
	})
	// .attr("x", function(d) {
	// 	return xScale(d[0]);
	// })
	// .attr("y", function(d) {
	// 	return yScale(d[1]);
	// })
	.attr("fill", function(d) {
		// return Math.sqrt(h - d[1]);
		return "#000";
	})
	.attr("font-size", function(d) {
		// return Math.sqrt(h - d[1]);
		return 10;
	})
	.attr("transform", transform(d3.zoomIdentity));

var svg1 = d3.select("svg");

svg1.call(d3.zoom().on("zoom", zoom));

function zoom() {
	var t1 = transform(d3.event.transform);
	var t2 = transform(d3.event.transform, true);
	text.attr("transform", t1);
	circle.attr("transform", t2);
}

function transform(t, s) {
	return function (d, i) {
		if (s) {
			return "translate(" + t.apply(d) + ") scale(" + t.k + ")";
		} else {
			return "translate(" + t.apply(d) + ")";
		}
	}
}

Comments