Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Streamgraph generator</title>
<!-- <link rel="stylesheet" type="text/css" href="style.css"> -->	</head>
	<body>
			<p>
				<button class="smart" onclick="change_layers()">Сгенерить удава</button>
			</p>

		<script src='https://d3js.org/colorbrewer.v1.js'></script>
		<script src="https://d3js.org/d3.v3.min.js"></script>
		<!-- <script src="d3.v3.min.js"></script> -->
<!-- <script src="script.js"></script> -->

	</body>
</html>
              
            
!

CSS

              
                body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 12px;
  
}

.stupid {
  position: absolute;
  left: 255px;
}
.smart {
  position: absolute;
  left: 100px;
}

form {
  right: 200px;
  top: 10px;
}

.axis path,
.axis line {
    fill: none;
    stroke: white;
    opacity: 0.25;
    shape-rendering: crispEdges;
}

.axis text {
    font-family: sans-serif;
    font-size: 11px;
}
              
            
!

JS

              
                // Переменные для страницы
var margin = {top:20, right:5, bottom:20, left:5,body:15},
    width = document.body.clientWidth - margin.left - margin.right - margin.body*2, 
    height = 500;

// Создаем форму для опций
var dropdown = d3.select("p")
  .attr("class","form")
  .append("form")
  .attr("name","opts");

// Добавляем в неё селектор для выбора палитры
dropdown.append("select")
  .attr("name","colors")
  .attr("onChange","change_color()") // При смене значения, вызываем функцию обновления цвета
  .selectAll("option")
  .data(Object.keys(colorbrewer))
  .enter().append("option")
  .attr("value",String)
  .text(String);

// // Добавляем селектор для выбора количества слоёв
// dropdown.append("input")
//  .attr("name","layers")
//   .attr("type","text")
//   .attr("value",n) // Количество слоёв по умолчанию
//   .style("width", "20px")
//   .attr("onChange","change_layers()")
//   .attr("hidden",""); // 



// Сохраняем текущие значения селекторов
var opts = document.opts,
    opts_c=opts.colors,
    c = opts_c.options[opts_c.selectedIndex].value;
// var n = document.opts.layers.value;// Количество слоёв
var colors = colorbrewer[c][6],
    color = d3.scale.ordinal()
    .range(colors);



// Переменные для удава
var n = 20;
 var m = 30, // number of samples per layer
    stack = d3.layout.stack().offset('silhouette'),
    layers0 = stack(d3.range(n).map(function() { return bumpLayer(m); }));


d3.select("body")
  .style("margin",margin.body + "px");

 //.attr("margin",'('+margin.top+','+margin.right+','+margin.bottom+','+margin.left+')')

var x = d3.scale.linear()
    .domain([0, m - 1])
    .range([0, width]);

var y = d3.scale.linear()
    .domain([0, d3.max(layers0, function(layer) {
      return d3.max(layer, function(d) {
        return d.y0 + d.y; 
      }); 
    })])
    .range([height, 0]);

var area = d3.svg.area()
    .interpolate('basis')
    .x(function(d) { return x(d.x); })
    .y0(function(d) { return y(d.y0); })
    .y1(function(d) { return y(d.y0 + d.y); });



// Рисуем удава
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height + margin.top + margin.bottom)
    .style("padding", margin.top+'px '+margin.right+'px '+margin.bottom+'px '+margin.left+'px');

svg.selectAll("path")
    .data(layers0)
  .enter().append("path")
    .attr("d", area)
    .style("fill", function() {
      return color(Math.random());
    })
    .on("mouseover", function(e){
       d3.select(this)
       .attr('stroke',function(){
         return d3.rgb(this.style.fill).darker(0.4)
       });
    })
    .on("click",function(){
      alert('[' + document.opts.layers.value + ' == ' + n + "] "+ " body: " + document.body.clientWidth + " " + window.width + " " + " html: " + document.body.scrollWidth + " Ширина svg: " + width);
    })
    .on("mouseout", function(){
     d3.select(this)
       .attr('stroke',"none");
    });

  // Добавляем оси
  var xAxis = d3.svg.axis()
                .scale(x)
                .orient("bottom")
                .ticks(30)
                .tickSize(-500,0);

  svg.append("g")
      .attr("class", "axis")
      .attr("transform", "translate(0," + (500) + ")")
      .call(xAxis);

<!-- /*setInterval('change_layers()',3000);*/ -->
  console.log(Math.round(Math.random()*Object.keys(colorbrewer).length));
//---------------------------FUNCTIONS-------------------------
function change_layers(){
	// рандомно выбираем цвет
  var random_color = Math.round(Math.random()*Object.keys(colorbrewer).length);
	var color = d3.scale.ordinal().range(colorbrewer[opts_c.options[random_color].value][6]);

  opts_c.options[random_color].selected = true;


// Создать новые данные
  var layers0 = stack(d3.range(n).map(function() { return bumpLayer(m); }));
// Уточнить функцию для подгонки высоты
  var y = d3.scale.linear()
    .domain([0, d3.max(layers0, function(layer) {
      return d3.max(layer, function(d) {
        return d.y0 + d.y; 
      }); 
    })])
    .range([height, 0]);
//Подогнать высоту
  var area = d3.svg.area()
    .interpolate('basis')
    .x(function(d) { return x(d.x); })
    .y0(function(d) { return y(d.y0); })
    .y1(function(d) { return y(d.y0 + d.y); });
  
// Обновить данные
    svg.selectAll("path")
    .data(layers0)
    .transition()
      .duration(2000)
    .attr("d", area)   // Рисуем нового удава
    .style("fill", function() {  // Заливаем выбранным цветом
      return color(Math.random()); 
    });
}

// Функция для обновления цвета
function change_color() {

  var color = d3.scale.ordinal()
  .range(colorbrewer[opts_c.options[opts_c.selectedIndex].value][6]); // Смотрим что выбрано в выпадашке и подбираем соответствующую палитру

    d3.selectAll("path") // Выбираем фигуру и обновляем цвета
     .data(layers0)
    .transition()
      .duration(1500)
      .style("fill", function() {
      return color(Math.random()); 
    });
    //alert(color); 
};

// Генератор данных
function bumpLayer(n) {

  function bump(a) {
    var x = 1 / (.1 + Math.random()),
        y = 2 * Math.random() - .5,
        z = 10 / (.1 + Math.random());
    for (var i = 0; i < n; i++) {
      var w = (i / n - y) * z;
      a[i] += x * Math.exp(-w * w);
    }
  }

  var a = [], i;
  for (i = 0; i < n; ++i) a[i] = 0;
  for (i = 0; i < 5; ++i) bump(a);
  return a.map(function(d, i) { return {x: i, y: Math.max(0, d)}; });
}
              
            
!
999px

Console