【问题标题】:d3.js, color gradient does not changed3.js,颜色渐变不改变
【发布时间】:2020-11-24 12:15:45
【问题描述】:

我正在尝试使用 d3 实现一个自定义组件来可视化数据。我正在使用 d3 渐变来渲染颜色。

添加另一个组件实例时,即使更改了Input() colorList,渐变的颜色也保持不变。有没有可能遗漏的东西?

代码示例如下: https://stackblitz.com/edit/spectrum-scale-component


//colorList = ['#9E0142', '#D53E4F','#090979']

<app-spectrum-scale
[data]="0.7"
[leftLabel]="'Feminine'"
[rightLabel]="'Masculine'"
[middleLabel]="'Neutral'"
[minVal]="-1"
[maxVal]="1"
[colorList]="['#9E0142', '#D53E4F','#090979']"
>
</app-spectrum-scale>  

//colorList = "['#9E0142', '#D53E4F',
                    '#F46D43', '#FDAE61',
                    '#FEE08B', '#FFFFBF',
                    '#E6F598', '#ABDDA4', 
                    '#66C2A5', '#6AA84F',
                    '#38761D']"

<app-spectrum-scale
[data]="0.55"
[leftLabel]="'Negative'"
[rightLabel]="'Positive'"
[middleLabel]="'Neutral'"
[minVal]="-1"
[maxVal]="1"
[colorList]="['#9E0142', '#D53E4F',
                    '#F46D43', '#FDAE61',
                    '#FEE08B', '#FFFFBF',
                    '#E6F598', '#ABDDA4', 
                    '#66C2A5', '#6AA84F',
                    '#38761D']"
>
</app-spectrum-scale>  

【问题讨论】:

  • 我尝试添加 ff 行代码以删除前一个 svg d3.select('svg').remove(); 的内容,但这最终删除了第一个组件,并重新创建了第二个组件

标签: angular d3.js svg


【解决方案1】:

解决方法是在组件初始化的时候给渐变样式添加一个唯一的id。这将确保渲染的组件将选择正确的渐变。

这里的工作代码:https://stackblitz.com/edit/spectrum-scale-component

this._id ='id' + (new Date()).getTime();

然后您可以将此 tempId 分配给“rect”填充属性

var tempColorList = this.colorList
var tempId = this._id;

var grad = this._chart.append('defs')
  .append('linearGradient')
  .attr('id', tempId)
  .attr('x1', '0%')
  .attr('x2', '100%')
  .attr('y1', '0%')
  .attr('y2', '0%');

grad.selectAll('stop')
  .data(tempColorList)
  .enter()
  .append('stop')
  .style('stop-color', function(d){ return d; })
  .attr('offset', function(d,i){
    return 100 * (i / (tempColorList.length - 1)) + '%';
  })

var gradValue = 'url(#' + tempId + ')'

var spectrum_bar = this._chart.append('rect')
  .attr('class', 'bg-rect')
  .attr('rx', 5)
  .attr('ry', 5)
  .style('opacity', 0.5)

// assign gradValue id here

  .style('fill', gradValue)
  .attr('height', 15)
  .attr('width', this._barWidth)
  .attr('x', 0)

【讨论】:

    猜你喜欢
    • 2010-12-17
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多