从d3获取模式并将其设置为div的边框

问题描述 投票:0回答:1

我为d3创建了一个模式:

d3.select('defs')
    .append('pattern')
    .attr('id', hatchId)
    .attr('width', 14)
    .attr('height', 14)
    .attr('patternUnits', 'userSpaceOnUse')
    .attr('patternTransform', 'rotate(45 0 0 )')
    .attr('fill', color)
    .append('rect')
    .attr('height', 14)
    .attr('width', 14);
d3.select(hatchId)
     .append('line')
     .attr('y2', 14)
     .attr('opacity', '0.3')
     .style('stroke', '#fff')
     .attr('stroke-width', 6);

并在c3.js选项中将其返回为颜色:

data: {
            type: 'bar',
            columns: [],
            types: {},
            axes: {},
            classes: {},
            color: function (color, d) {
                .....
                return `url(#${hatchId})`;
            },
        },

它看起来像这样

enter image description here

但我需要添加具有这种模式的元素 - 例如,带边框的图例

我尝试创建:

`<div style="border-color: url(#${hatchId});">Name</div>`

找不到图案

是否有可能从d3获取模式并在除c3之外的其他地方使用它?

javascript d3.js svg c3.js
1个回答
2
投票

是的,这是可能的。

由d3创建的pattern只是常规的SVG。您可以将其作为填充或描边应用于SVG形状,但不能将其应用于HTML。

<svg viewBox="0 0 230 100" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <pattern id="star" viewBox="0,0,10,10" width="5%" height="5%">
      <polygon points="0,0 2,5 0,10 5,8 10,10 8,5 10,0 5,2"/>
    </pattern>
  </defs>
  <circle cx="50"  cy="50" r="50" fill="url(#star)"/>
  <rect x="120"  width="100" height="100" fill="none" stroke-width="6" stroke="url(#star)"/>
</svg>
© www.soinside.com 2019 - 2024. All rights reserved.