Using google charts (bars), can I make de bar color linear gradient?

依然范特西╮ 提交于 2020-01-03 05:17:08

问题


I'm using a bar chart and I need that the bars to be gradient rather than solid colors.In the code, you can see that I add "role: style" and after a solid color, but I need that the to have a linear gradient.

function drawChart2() {
    var data = google.visualization.arrayToDataTable([
        ["Element", "Difference", {
            role: "style"
        }],
        ['Mg', 1.2 , "#1aab54"]           
    ]);

    var view = new google.visualization.DataView(data);
    view.setColumns([0, 1, {
        calc: "stringify",
        sourceColumn: 1,
        type: "string",
        role: "annotation"
    },
    2]);

    var options = {
        title: "",
        legend: {position: 'none'},
        bar: {
            groupWidth: "50%"
        },
        hAxis: {
          viewWindowMode:'explicit',
          viewWindow: {
          max:2,
          min:0.5
          },
          ticks: [{ v: 0.5, f: 'low'}, { v: 1, f: 'middle'}, {v: 1.5, f: 'high'}],
    },
    };
    var chart_area = document.getElementById("barchart_values2");
    var chart = new google.visualization.BarChart(chart_area);
    google.visualization.events.addListener(chart, 'ready', function(){
 chart_area.innerHTML = '<img src="' + chart.getImageURI() + '" class="img-responsive">';
});
    chart.draw(view, options);

}


回答1:


no options for gradient fill,
but you can add your own...

first, add your gradient definition to the html somewhere.
this element should not be hidden with display: none,
otherwise, some browsers may ignore it.
setting the size to zero pixels seems to work.

<svg style="width:0;height:0;position:absolute;" aria-hidden="true" focusable="false">
  <linearGradient id="my-gradient" x2="1" y2="1">
    <stop offset="0%" stop-color="#5de694" />
    <stop offset="50%" stop-color="#1aab54" />
    <stop offset="100%" stop-color="#0c5228" />
  </linearGradient>
</svg>

next, we need to be able to identify the <rect> element used for the bar.
we can use the color style.

['Mg', 1.2 , '#1aab54']  // <-- find element by color

find the <rect> element and set the fill attribute.
normally, we could set the gradient fill on the chart's 'ready' event,
but we have to use a MutationObserver, and set the fill every time the svg is mutated (drawn / hovered).

// create observer
var observer = new MutationObserver(function () {
  var svg = chart_area.getElementsByTagName('svg')[0];
  svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');

  // add gradient
  Array.prototype.forEach.call(chart_area.getElementsByTagName('rect'), function(rect) {
    if (rect.getAttribute('fill') === '#1aab54') {
      rect.setAttribute('fill', 'url(#my-gradient) #1aab54');
    }
  });
});
observer.observe(chart_area, {
  childList: true,
  subtree: true
});

however, I was not able to get the gradient to come thru in the image, maybe html2canvas will do a better job.

see following working snippet...

google.charts.load('current', {
  packages:['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Element', 'Difference', {
      role: 'style'
    }],
    ['Mg', 1.2 , '#1aab54']
  ]);

  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1, {
    calc: 'stringify',
    sourceColumn: 1,
    type: 'string',
    role: 'annotation'
  }, 2]);

  var options = {
    title: '',
    legend: {position: 'none'},
    bar: {
      groupWidth: '50%'
    },
    hAxis: {
      viewWindowMode:'explicit',
      viewWindow: {
        max:2,
        min:0.5
      },
      ticks: [{ v: 0.5, f: 'low'}, { v: 1, f: 'middle'}, {v: 1.5, f: 'high'}],
    },
  };
  var chart_area = document.getElementById('barchart_values2');
  var chart = new google.visualization.BarChart(chart_area);
  google.visualization.events.addListener(chart, 'ready', function(){

    // create observer
    var observer = new MutationObserver(function () {
      var svg = chart_area.getElementsByTagName('svg')[0];
      svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');

      // add gradient
      Array.prototype.forEach.call(chart_area.getElementsByTagName('rect'), function(rect) {
        if (rect.getAttribute('fill') === '#1aab54') {
          rect.setAttribute('fill', 'url(#my-gradient) #1aab54');
        }
      });

      // create chart image
      var svgContent = new XMLSerializer().serializeToString(svg);
      var domURL = window.URL || window.webkitURL || window;
      var imageURL = domURL.createObjectURL(new Blob([svgContent], {type: 'image/svg+xml'}));
      var image = document.getElementById('image_div').appendChild(new Image());
      image.src = imageURL;
    });
    observer.observe(chart_area, {
      childList: true,
      subtree: true
    });

  });
  chart.draw(view, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>

<div id="barchart_values2"></div>
<div id="image_div"></div>

<svg style="width:0;height:0;position:absolute;" aria-hidden="true" focusable="false">
  <linearGradient id="my-gradient" x2="1" y2="1">
    <stop offset="0%" stop-color="#5de694" />
    <stop offset="50%" stop-color="#1aab54" />
    <stop offset="100%" stop-color="#0c5228" />
  </linearGradient>
</svg>


来源:https://stackoverflow.com/questions/55171632/using-google-charts-bars-can-i-make-de-bar-color-linear-gradient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!