D3 Basics

Element selection

  • Select from the CSS selector
  • Select by DOM object
  • Get the title element from native JS
  • multi-select
  • Filter element
<h1 id="title">
    <p></p>
    <p></p>
    <p></p>
    <p></p>
</h1>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script>
    d3.select("#title").classed('sky'.true);
    d3.select("p").classed('sky'.true);
    const title = document.querySelector("#title");
    d3.select(title).classed('sky'.true);
    
    d3.selectAll('p').classed('sky'.true);
    d3.selectAll('p:nth-child(2)').classed('sky'.true);
    d3.selectAll('p:nth-child(even)').classed('sky'.true);
    
    d3.selectAll('p').filter((ele, ind) = > (ind%2) = =1).classed('sky'.true);;
    
    const n = [1.2.3];
    d3.selectAll('p').filter((ele, ind) = > n.includes(ind)).classed('sky' ,true);
</script>
Copy the code

Setting element Styles

  • Set the DOM inline style

    Style Inline style

    Add and remove class classed

    Attr sets the property, overwriting the value of the previous property

  • The style() method sets the title color

  • The attr() method changes the title color by setting the style property

  • Classed (class, true | false) method to add or delete the title of the class

  • The attr() method sets the class property

  • Use the style callback to make all p elements with even lines blue

  • Dynamically set the font size of the P element using data binding

const title = d3.select('#title');
title.style('color'.'red');
title.attr('style'.'color: red');
title.classed('sky'.true);
// The former will not override, while the latter will override the previous class attribute value
title.attr('class'.true);

d3.selectAll('p').style('color'.(ele, ind) = > ind%2 ? 'red' : 'black');

const data = [12.16.17.24.56];
d3.selectAll('p').data(data).style('font-size'.(ele, ind) = > {
    return `${ele}px`
});
d3.selectAll('p').data(data).style('font-size'.(ele, ind) = > `40px`);
Copy the code

Setting element attributes

  • Setting DOM Properties

    Attr sets common built-in properties and custom properties

    Property Sets special built-in properties

  • Based on the answer, select the corresponding option

d3.selectAll('label').attr('class'.'opt');

const answer = [0.1];
d3.selectAll('input')
	.filter((ele, ind) = > answer.includes(ind))
	.property('checked' ,true);
Copy the code

Setting element content

  • Text Text content
  • HTML HTML content
const title = d3.select('#title');
const titleText = "123";
const p = ` 

`
; title.text(titleText); title.html(p); Copy the code

Add or delete elements

  1. Add a DOM element
    • Append appends the named child element to the end of the current selection set
    • Insert pre-element, which can be declared to be added before the element
    • Data + Join adds elements in full coverage
    • Data + Enter + append adds elements by difference
<body>
<h1 id="title">Qinyuanchun · Changsha</h1>
<article id="cont"></article>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script>
    const arr=[
        'By Chairman MAO'.'Independent cold autumn, Xiangjiang North, Orange island head. '.'Look at the mountains, all dyed; They are thriving. '.'Eagles fly in the sky, fish hang in the shallow, all kinds of frosty day race for freedom. '.'Who is in charge of the ebb and flow of the boundless earth? '.'Bring me back to swim. Memories of the past are thick. '.'Just the young students, in the prime of life; Scholarly spirit, violent party. '.'Pointing jiangshan, stirring up the text, the year of ten thousand marquis of dung. '.'Have you ever remembered to strike water in the middle of the stream? '
    ]
    const cont=d3.select('#cont');
    cont.append('p')
    	.text('Independent cold autumn, Xiangjiang North, Orange island head. -- -- -- -- -- -- -- -- -- ')
    	.attr('id'.'p1');
    cont.insert('p'.'#p1')
    	.text('123');
    cont.selectAll('p')
    	.data(arr)
    	.join('p')
    	.text(d= >d)
    const.selectAll('p')
    	.data(arr)
    	.enter()
    	.append('p')
    	.text(d= >d)
    
</script>
</body>
Copy the code
  1. Deleting DOM elements
d3.select('p').remove();
// Delete the first element
Copy the code

svg

SVG drawing

  • SVG root node
    1. Version SVG version
    2. XMLNS namespace http://www/w3.org/2000/svg
    3. Width | height SVG canvas size, such as 400, 400
    4. A viewBox is always fully displayed on the canvas, and its graphics are displayed proportionally based on the width and height of the viewBox
<svg version="1.2"
     xmlns="http://www.w3.org/2000/svg"
     width="400"
     height="400"
     viewBox="0 0 400 400"
>
    <! The position of the far point in the viewBox is based on the width and height of the view and the total SVG layer-to-height ratio. The width and height of the built-in elements are converted based on this ratio.
	<rect width="400" height="400" fill="red" />
</svg>
Copy the code
  • SVG drawing
    • rect
    • circle
    • path
      • A straight line
      • The circular arc
      • Quadratic Bessel curve
      • Cubic Bezier curves
      • The circular container
<! - the rect: rectangular width on the upper left corner point position x | y | height size -- -- >
<rect x="100"
      y="100"
      width="400"
      height="400"
      fill="red"
/>

<! Cx | - circle: cy center position radius r - >
<circle cx="300"
        cy="300"
        r="100"
        fill="red"
/>

<! Path - the path path: d shape, capital letters for the absolute point positioning, lowercase letters for relative point positioning starting point: M | M the next point: L | L arc: A | A quadratic bezier curve: Q | Q, T | T three times bezier curve: C | C, S | | S closed path Z Z - >


<path d=" M 300 300 L 500 300 "
      fill="none"
      stroke="# 000"
      stroke-width="10"
      stroke-dasharray="30 10"
/>

<! - arc: A | A, such as 300, 300, A 150 M 200 0 0 0 500 300 rx and ry radius x axis - rotation axis x [0, Large - the arc - 360] flag whether show maximum arc sweep - where is the flag arc side 0 | 1 x y end points -- -- >
<path d=" M 300 300 A 150 200 20 1 0 500 300 "
      fill="none"
      stroke="# 000"
      stroke-width="5"
/>

<! Put it in a container, and pull out the common attributes inside the container tag.
<g fill="none" stroke="# 000">
        <path d=" M 100 400 L 200 400 200 200 300 200 400 400 500 400 "

              stroke-width="2"
              stroke-dasharray="3"
        />
        <path d=" M 100 400 C 200 400 200 200 300 200 S 400 400 500 400 600 200 700 200 "
              stroke-width="10"
        />
    </g>
Copy the code

Quadratic Bessel curve

<! | - quadratic bezier curve: Q Q, such as M, 100, 400 Q, 200, 100, 300 400 cpx1 cpy1 control point x y end points Quadratic bezier continue: T | T, such as T 400-500 - >
<path d=" M 100 400 L 200 100 300 400 "
	fill="none"
	stroke="# 000"
	stroke-width="2"
	stroke-dasharray="3"
/>
<path d=" M 100 400 Q 200 100 300 400 T 500 400 700 400 "
	fill="none"
	stroke="# 000"
	stroke-width="5"
/>
<circle cx="100" cy="400" r="10" fill="red" />
<circle cx="200" cy="100" r="10" fill="red" />
<circle cx="300" cy="400" r="10" fill="red" />
<circle cx="500" cy="400" r="10" fill="red" />
<circle cx="700" cy="400" r="10" fill="red" />
Copy the code

For a continuous period, you just have to plot one point, (the last point x + period T, the last point y).

Cubic Bezier curves

<! - three times a bezier curve: C | C, such as M, 100, 400 C, 200, 400, 200, 200, 300, 200 cpx1 cpy1 control points 1 cpx2 cpy2 control point 2 x y end points Bezier curve is a continuation of the three times: S | S, such as 400, 400, 500, 400 - S - >
<path d=" M 100 400 L 200 400 200 200 300 200 400 400 500 400 600 200 700 200 "
	fill="none"
	stroke="# 000"
	stroke-width="2"
	stroke-dasharray="3"
/>
<path d=" M 100 400 C 200 400 200 200 300 200 S 400 400 500 400 600 200 700 200 "
	fill="none"
	stroke="# 000"
	stroke-width="5"
/>
<circle cx="100" cy="400" r="10" fill="red" />
<circle cx="200" cy="400" r="10" fill="red" />
<circle cx="200" cy="200" r="10" fill="red" />
<circle cx="300" cy="200" r="10" fill="red" />
<circle cx="400" cy="400" r="10" fill="blue" />
<circle cx="500" cy="400" r="10" fill="blue" />
<circle cx="600" cy="200" r="10" fill="blue" />
<circle cx="700" cy="200" r="10" fill="blue" />
Copy the code

Periodic rule: The next four points plot the next half-periodic graph

SVG style

  • Coloring area
    • Fill fills the area, default blank
    • The stroke area defaults to None
<circle cx="300"
        cy="300"
        r="200"
        fill="red"
/>
Copy the code
  • Color way

    • Pure color
    <circle cx="300"
            cy="300"
            r="200"
            fill="red"
    />
    Copy the code
    • gradient

      • Linear gradient
      <! - that linearGradient linear gradient gradientTransform gradient transform to https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function Rotate (a) rotate [0,360] translate(x,y) scale(sx,sy) zoom stop color node offset [0,1] stopcolor color assignment url(id) -->
      <defs>
      	<linearGradient id="gr"
                          gradientTransform="rotate(30)"
          >
              <stop offset="0" stop-color="#fff"/>
              <stop offset="0.5" stop-color="#00acae"/>
              <stop offset="1" stop-color="#fff" />
          </linearGradient>
      </defs>
      <circle cx="300"
              cy="300"
              r="200"
              fill="url(#gr)"
      />
      Copy the code
      • Radial gradient
      <! --radialGradient stop color offset [0,1] stop color -->
      <defs>
      	<radialGrandient id="gr">
          	<stop offset="0" stop-color="#fff"/>
              <stop offset="0.5" stop-color="#00acec"/>
              <stop offset="1" stop-color="#fff"/>
          </radialGrandient>
      </defs>
      <circle cx="300"
              cy="300"
              r="200"
              fill="url(#gr)"
      />
      Copy the code
    • texture

      • Note the insert image margins (width and height must be the same as the width and height of the viewBox)
      <! The size of the texture element is recommended to use 100% polygon points. Such as 0, 0, 20, 50, 0100 reached 50, 100100, 80, 50, 100, 0, 50, 20 image picture href address x | y position widht | height wide high -- >
      
      <polygon points="0,0, 20,50,100 50,80 100,100 80, 100 80,50 100,0 50,20"/>
      <defs>
      	<pattern width="30%"
                   height="30%"
                   viewBox="0 0 100 100"
                   id="pt"
          >
              <image href="./images/rose/jpg"
                     width="100"
                     height="100"
              />
          </pattern>
      </defs>
      <circle cx="300"
              cy="300"
              r="200"
              fill="url(#pt)"
      />
      
      
      Copy the code

SVG encapsulation

<body>
<div id="main"></div>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script>
    const main = d3.select('#main');
    function Draw(dom) {
        return function(shape, option) {
            const obj = dom.append(shape);
            for(let [key, val] of Object.entries(option)) {
                obj.attr(key, val);
            }
            returnobj; }}const svg = Draw(main)('svg', {
        version: 1.2.xmlns: 'https://www.w3.org/2000/svg'.width: '100%'.height: '100%'.viewBox: '- 400-400 800 800
    })
    // Create a drawing method using SVG as a container
    const draw = Draw(svg);
    draw('rect', {
        x: -200
    })
</script>
</body>
Copy the code
	const rectCom={
        x: -200.y:0.width:400.height:200,
    }
	draw('rect', {... rectCom,fill:red
    });
Copy the code

Draw a robot using the encapsulation method described above

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The robot - d3</title>
    <style>
        html{height: 100%}
        body{height: 100%;margin: 0; }#main{
            width: 100%;
            height: 100%;
            background-color: antiquewhite;
        }
    </style>
</head>
<body>
<div id="main"></div>
<script src="https://d3js.org/d3.v6.min.js"></script>
<script>
    /* Get the main container */
    const main=d3.select('#main')

    /* Create SVG in the main container and set its properties */
    / * const SVG = main. Append (' SVG). Attr (' version, 1.2). The attr (' XMLNS ', 'http://www.w3.org/2000/svg'). Attr (' width ', '100%') .attr('height','100%') .attr('viewBox','-400 -400 800 800')*/

    const svg=Draw(main)('svg', {version:1.2.xmlns:'http://www.w3.org/2000/svg'.width:'100%'.height:'100%'.viewBox:'- 400-400 800 800
    })

    /* Create drawing function Draw, take DOM container as parameter, return drawing method * Drawing method take shape and configuration option as parameter * append method add graph obj to container * for... Of...... To traverse the key value pairs of Object.entries * set the property of the graph obj using the attr method * return the graph obj * */
    function Draw(dom) {
        return function(shape,option){
            const obj=dom.append(shape)
            for(let [key,val] of Object.entries(option)){
                obj.attr(key,val)
            }
            return obj
        }
    }

    /* Create a SVG container drawing method draw*/
    const draw=Draw(svg)

    /* Draw a graph... * /
    draw('rect', {x: -200.y:0.width: 400.height: 200.fill:'red'
    })
    draw('rect', {x: -200.y:0.width: 400.height: 200.fill:'none'.stroke:'# 000'.'stroke-width':40,
    })
    draw('rect', {x: -200.y:50.width: 400.height: 60.fill:'antiquewhite'
    })
    draw('path', {d:` M -100 150 L 100 150 `.fill:'none'.stroke:'# 000'.'stroke-width':40,
    })
    draw('circle', {cx: -100.cy:80.r: 20.fill:'red'
    })
    draw('path', {d:` M 80 90 A 20 20 0 0 1 120 90 `.fill:'red'
    })
    draw('path', {d:` M -200 -200 C -100 -200 -100 0 0 0 S 100 -200 200 -200 `.fill:'none'.stroke:'# 000'.'stroke-width':40,})</script>
</body>
</html>
Copy the code