D3 Exploration - Step 1

D3入门学习1

创建SVG容器

  • svg的相关内容: MDN

基本使用

const svg = d3
  .select('div') // other CSS Selectors~~
  .append("svg")
  .style({ 
    backgound: 'pink''
  })
  .attr("width", '80vw')
  .attr("height", '90vh');

效果:

D3 Exploration - Step 1

封装 D3Svg 类

用法

new D3Svg([opts]);
opts.xx说明
container装载svg元素的容器元素,默认在body元素创建一个空的div容器
widthsvg容器的宽度
heightsvg容器的高度
stylesvg容器的样式配置
wrapperContainerStyle最外层容器的样式配置
  • Creates and returns a svg element that is attached to elem. elem can be a DOM object or a selector.
  • The opts object will set the width and height of the svg if set, otherwise these attributes will remain null.
class D3Svg {

  private svg: d3.Selection<any>;
  private wrapperContainer: HTMLElement | HTMLDivElement;

  constructor(
    options: ISvgContainerOptions = {},
  ) {
    const container = options.container || DEFAULT_CONTAINER();
    const width = options.width || DEFAULT_CONTAINER_WIDTH;
    const height = options.options || DEFAULT_CONTAINER__HEIGHT;
    const { style, wrapperContainerStyle } = options;

    /**
     * initialize wrapperContainer
     */
    this.wrapperContainer = container;
    if (wrapperContainerStyle) {
      this.addWrapperStyle(wrapperContainerStyle);
    }
    this.svg = d3
      .select(this.wrapperContainer)
      .append("svg")
      .style({ ...style })
      .attr("width", width)
      .attr("height", height);
  }

  getSize(): IBoxSize {
    if (this.svg) {
      // Notice: it's SVGSVGElement
      const node = this.svg.node() as SVGSVGElement;
      const box = node.getBoundingClientRect();
      return box;
    }
    return {
      width: 0,
      height: 0,
    };
  }
  
  public addWrapperStyle(styles: { [key: string]: string }) {
    Object.keys(styles).map(key => {
      this.wrapperContainer.style.setProperty(key, styles[key]);
    });
  }
}

下一篇,开始添加我们的图像~~

svg

相关推荐