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.

            
              <!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>
            
          
!
            
              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;
}
            
          
!
            
              // Переменные для страницы
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
🕑 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