1

enter image description here

I am interested in learning how to create a transparent mask with d3.js.

http://jsfiddle.net/59bunh8u/35/

This is where I am up to - how would I create a subtraction mask on the red rectangle - also how could you style the red rectangle to take on more of a multiply style property?

$(document).ready(function() {

  var el = $(".mask"); //selector

  // Set the main elements for the series chart
  var svg = d3.select(el[0]).append("svg")
    .attr("class", "series")
    .attr("width", "800px")
    .attr("height", "500px")
    .append("g")
    .attr("transform", "translate(0,0)")


  var rect = svg
    .append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("width", 500)
    .attr("height", 500)
    .style("fill", "red")
    .style('opacity', 0.75)

  var rect = svg
    .append("circle").attr("cx", 250).attr("cy", 250).attr("r", 125).style("fill", "white");


});
The Old County
  • 89
  • 13
  • 59
  • 129

1 Answers1

5

You need an SVG mask. Feel free to play with it to tweak the parameters:

  var mask = svgroot
     .append("defs")
     .append("mask")
     .attr("id", "myMask");

  mask.append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("width", 500)
    .attr("height", 500)
    .style("fill", "white")
    .style("opacity", 0.7);        

  mask.append("circle")
    .attr("cx", 300)
    .attr("cy", 300)
    .attr("r", 100);

Modified example: http://jsfiddle.net/59bunh8u/40/

See also SVG clipPath to clip the *outer* content out

Community
  • 1
  • 1
Nixie
  • 637
  • 4
  • 9
  • that is great -- how to fill the rectangle to take on more multiply/photoshop properties – The Old County Sep 07 '16 at 11:12
  • 1
    I do not know how Photoshop does its multiplication, but 'mask' element performs some sort of a multiplication, according to https://www.w3.org/TR/SVG/masking.html#Masking. Please check if SVG filters (feBlend element) help achieving a multiplication similar to Photoshop: https://www.w3.org/TR/SVG/filters.html#feBlendElement – Nixie Sep 07 '16 at 13:17
  • -- I think the masking is done - but if you have more ideas on fill/color tweaking -- rather than using hex for fill - what about using rgba values – The Old County Sep 07 '16 at 15:12
  • Oh, yes, that is a bug in my code. I should have used fill="white" with opacity=0..1 , to be clear. See http://jsfiddle.net/59bunh8u/40/. This mask converts the rect and the circle inside into black and white and then takes opacity from that image (0 - transparent, 1 - opaque). The rectangle inside was red, and red converted to something on black-n-white scale, this is where opacity was taken from. – Nixie Sep 07 '16 at 15:36
  • I've taken this further to try and enhance this codebase -- give it more complexity and responsiveness enhancement - http://stackoverflow.com/questions/39380789/d3-js-transparent-shape-tesselations-complex-subtractions – The Old County Sep 08 '16 at 00:19