2

I'm trying to add a mask to AreaChart and have found out that created mask is applied (and displayed) only when it's defined within <defs> section of the svg document generated by Google Charts API. I created an EventListener for the 'ready'-event, which appends <mask> to <defs> but it had no success.

The most strange thing is that I can see the appended <mask> when I inspect <svg> with Firefox Webmaster Tools and when I edit <defs> in browser 'as HTML', change something (eg: add additional space between any tags or attributes) and save — the mask is applied to the path of my chart, but I don't understand why it is not applied when the API draws the chart.

Here is some code:

google.visualization.events.addListener(chart, 'ready', function () {
    var mask = chart_placeholer.querySelector('defs > mask#mask-stripe');

    if(!mask) {
        mask = document.createElement('mask');
        mask.setAttribute('id', 'mask-stripe');

        // Note: there is no difference whether I create `<rect>` using createElement
        // and append, or create it with innerHTML — result is always the same.

        mask.innerHTML = '<rect x="0" y="0" width="100%" height="100%" fill="url(#pattern-stripe)"/>';
        chart_placeholer.getElementsByTagName('defs')[0].appendChild(mask);
     }
}

I also have code which changes the attributes fill and mask of the <path>, and it works fine, so there is no need to put that code here. The problem is that that mask is applied to path only after I find the definition of the mask with HTML Inspector, make some irrelevant changes and save it.

Here is an attached image to make the explanation more clear:

Rodion Baskakov
  • 636
  • 4
  • 14
  • 1
    In order to create a new element in SVG you are using [document.createElementNS()](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS). Also to set attributes you may need the [setAttributeNS](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttributeNS) – enxaneta Nov 21 '19 at 06:37
  • 1
    Thank you, you made my day! You should definitely make this an answer – Rodion Baskakov Nov 21 '19 at 06:59
  • Thank you so much for your comment. I've answered so often this question that I'm ashamed to answer it one more time. [For example here:](https://stackoverflow.com/questions/52901394/creating-svg-use/52903316#52903316) – enxaneta Nov 21 '19 at 07:40
  • 1
    I googled many times and used different search phrases, but didn't find that answer. Maybe that was because all my queries contained 'mask' keyword. – Rodion Baskakov Nov 21 '19 at 08:19

0 Answers0