You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Billboard.js(Angular)实现交替条形图:单深色单阴影填充

实现Billboard.js交替条形(实心/斜纹阴影)方案

要实现单个系列内条形交替使用实心和斜纹阴影填充,不需要全局设置color.tiles,而是在图表渲染完成后通过D3精准控制每个条形的填充样式,具体步骤如下:

1. 分离斜纹图案创建逻辑

单独定义创建斜纹图案的函数,并将图案添加到SVG的defs区域(SVG需通过defs复用图案资源):

const createHatchPattern = () => {
  const pattern = d3
    .select(document.createElementNS(d3.namespaces.svg, 'pattern'))
    .attr('patternUnits', 'userSpaceOnUse')
    .attr('width', '10')
    .attr('height', '10')
    .attr('id', 'hatch-pattern'); // 给图案设置唯一ID用于引用

  const g = pattern
    .append('g')
    .attr('fill-rule', 'evenodd')
    .append('g')
    .attr('fill', 'rgb(155, 169, 206)');

  g.append('polygon').attr('points', '6 0 10 0 0 10 0 6');
  g.append('polygon').attr('points', '10 6 10 10 6 10');
  
  // 将图案添加到目标容器的SVG defs中
  d3.select('#colorTiles2 svg defs').node().appendChild(pattern.node());
};

2. 初始化图表并设置默认实心样式

全局color.pattern设置为实心深色,让所有条形默认使用实心填充:

// base css
import 'billboard.js/dist/theme/insight.css';
import bb from 'billboard.js';
import * as d3 from 'd3';

// 初始化斜纹图案
createHatchPattern();

const chart = bb.generate({
  data: {
    json: {
      data1: [15, 23],
    },
    types: {
      data1: 'bar',
    },
  },
  bar: {
    padding: 50,
  },
  color: {
    pattern: ['#002781'], // 默认实心深色
  },
  bindto: '#colorTiles2',
  onrendered: function() {
    // 渲染完成后处理条形填充
    const bars = d3.select('#colorTiles2 .bb-bar rect');
    
    // 交替设置:索引为奇数的条形使用斜纹(可根据需求改为偶数)
    bars.each(function(_, index) {
      if (index % 2 === 1) {
        d3.select(this).attr('fill', 'url(#hatch-pattern)');
      }
    });
  }
});

3. 核心逻辑说明

  • 通过onrendered事件确保图表完全渲染后再操作DOM,避免元素未加载的问题。
  • 使用D3选择器选中所有条形的rect元素,通过索引判断实现交替样式:
    • index % 2 === 1表示第二个、第四个...条形使用斜纹
    • 若需要第一个、第三个...使用斜纹,改为index % 2 === 0即可
  • 斜纹图案通过ID引用,确保只有指定条形应用阴影效果,其余保持实心。

内容的提问来源于stack exchange,提问作者Mahesh Dharwad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:37:46