block by harrystevens e9431103a6814bf8bddb82f82873935b

Fun with Linear Gradients II

Full Screen

This block uses SVG’s linearGradient element and D3 selections to create a linear gradient. Rather than having just two colors, this gradient uses a six-color rainbow spectrum.

Drag the circles to change the gradient’s orientation.

index.html

<html>
  <head>
    <style>
      body {
        margin: 0;
      }

      .position-circle {
        stroke: #000;
        stroke-width: 2px;
        fill: #3a403d;
        cursor: all-scroll;
      }
    </style>
  </head>
  <body>
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <script>
      var width = window.innerWidth, height = window.innerHeight;

      var colors = ["#ff0000", "#ffb400", "#fff800", "#02ff00", "#005fff", "#9a01ff"];

      var position = [[.1, .1], [.9, .9]];

      var svg = d3.select("body").append("svg")
          .attr("width", width)
          .attr("height", height);

      var defs = svg.append("defs");

      var gradient = defs.append("linearGradient")
          .attr("id", "linear-gradient");

      colors.forEach(function(d, i){

        gradient.append("stop")
            .attr("offset", i / (colors.length - 1) * 100 + "%")
            .attr("stop-color", colors[i]);

      });

      svg.append("rect")
          .attr("class", "gradient-rectangle")
          .attr("x", "0")
          .attr("y", "0")
          .attr("width", width)
          .attr("height", height)
          .style("fill", "url(#linear-gradient)");

      changeOrientation(position);

      position.forEach(function(d, i){

        svg.append("circle")
            .attr("class", "position-circle")
            .attr("data-which", i)
            .attr("cx", width * position[i][0])
            .attr("cy", height * position[i][1])
            .attr("r", "20")
            .call(d3.drag(d)
              .on("drag", function(){

                var x = d3.event.x, y = d3.event.y;
                d3.select(this).attr("cx", x);
                d3.select(this).attr("cy", y);

                if (d3.select(this).attr("data-which") == 0) {
                  position[0][0] = x / width;
                  position[0][1] = y / height;
                } else {
                  position[1][0] = x / width;
                  position[1][1] = y / height;
                }

                changeOrientation(position);

              }));

      });

      function changeOrientation(position){
        gradient
            .attr("x1", position[0][0] * 100 + "%")
            .attr("y1", position[0][1] * 100 + "%")
            .attr("x2", position[1][0] * 100 + "%")
            .attr("y2", position[1][1] * 100 + "%");
      }

    </script>
  </body>
</html>