block by javidhsueh 6314335

6314335

Full Screen

SVG Essentials – Filters

This is a recreation (for the purpose of tinkering with an implementation in d3.js) of the example from the book SVG Essentials by J. David Eisenberg.

The <feColorMatrix> element allows to change color values in a following way.

<filter id="glow">
  <feColorMatrix type="matrix" values=
     "0 0 0 red   0
      0 0 0 green 0
      0 0 0 blue  0
      0 0 0 1     0"/>
  <feGaussianBlur stdDeviation="number" result="coloredBlur"/>
  <feMerge>
    <feMergeNode in="coloredBlur"/>
    <feMergeNode in="SourceGraphic"/>
  </feMerge>
</filter>

index.html

<!doctype html>
<meta charset="utf-8">
<title>Glow Filter</title>

<style>
svg {
  font-family: sans-serif;
  font-weight: bold;
}
</style>

<script src="//mbostock.github.com/d3/d3.js?2.9.6"></script>
<script src="glow.js"></script>

<body>

<script>
var myGlow = glow("myGlow").rgb("#0f0").stdDeviation(4);

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

svg.append("text")
    .attr("x", 50).attr("y", 100)
    .attr("font-size", "48px")
    .attr("fill", "#0f0")
    .text("Spring Flower")
    .style("filter", "url(#myGlow)");

svg.append("circle")
    .attr("cx", 450).attr("cy", 85)
    .attr("r", 50)
    .attr("fill", "#ff0")
    .style("filter", "url(#myGlow)");
</script>

glow.js

function glow(url) {
  var stdDeviation = 2,
      rgb = "#000",
      colorMatrix = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0";

  if (!arguments.length) {
    url = "glow";
  }

  function my() {

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

    var filter = defs.append("filter")
        .attr("id", url)
        .attr("x", "-20%")
        .attr("y", "-20%")
        .attr("width", "140%")
        .attr("height", "140%")
      .call(function() {
        this.append("feColorMatrix")
            .attr("type", "matrix")
            .attr("values", colorMatrix);
        this.append("feGaussianBlur")
             // .attr("in", "SourceGraphics")
            .attr("stdDeviation", stdDeviation)
            .attr("result", "coloredBlur");
      });

    filter.append("feMerge")
      .call(function() {
        this.append("feMergeNode")
            .attr("in", "coloredBlur");
        this.append("feMergeNode")
            .attr("in", "SourceGraphic");
      });
  }

  my.rgb = function(value) {
    if (!arguments.length) return color;
    rgb = value;
    color = d3.rgb(value);
    var matrix = "0 0 0 red 0 0 0 0 0 green 0 0 0 0 blue 0 0 0 1 0";
    colorMatrix = matrix
      .replace("red", color.r)
      .replace("green", color.g)
      .replace("blue", color.b);

    return my;
  };

  my.stdDeviation = function(value) {
    if (!arguments.length) return stdDeviation;
    stdDeviation = value;
    return my;
  };

  return my;
}