How to use SVG gradients to display varying colors relative to the size of the colored region

前端 未结 1 1088
既然无缘
既然无缘 2021-01-05 14:21

I\'m using SVG and D3 to create bar graphs and have a question concerning how to color them. I\'ve searched many questions on this site and others and haven\'t yet found any

相关标签:
1条回答
  • 2021-01-05 14:44

    This is simple to implement but a bit hard to grasp, you need to specify that the gradient units are userSpaceOnUse and then define the region where you want it to apply through x1, x2, y1, y2:

    var gradient = svg
        .append("linearGradient")
        .attr("y1", minY)
        .attr("y2", maxY)
        .attr("x1", "0")
        .attr("x2", "0")
        .attr("id", "gradient")
        .attr("gradientUnits", "userSpaceOnUse")
    
    gradient
        .append("stop")
        .attr("offset", "0")
        .attr("stop-color", "#ff0")
    
    gradient
        .append("stop")
        .attr("offset", "0.5")
        .attr("stop-color", "#f00")
    

    You can see a demo here: http://jsfiddle.net/ZCwrx/

    0 讨论(0)
提交回复
热议问题