Visualization D3.js drawing data charts (a) to make a simple graph

canvas

  The premise is to have a drawing canvas, HTML 5 provides two strong "canvas": SVG and Canvas.

SVG

  SVG, refers to Scalable Vector Graphics (Scalable Vector Graphics), for describing two-dimensional vector graphics in a graphical format, developed by the World Wide Web Consortium open standards.
  SVG uses XML to define the graphics format, in addition to previous versions of IE8, the vast majority of browsers support SVG,
can be directly embedded into HTML SVG text display.

SVG features

  1. SVG drawing a vector, thus amplifying the image is not distorted
  2. Based on XML, you can add JavaScript event handlers for each element
  3. Each graphics are treated as objects, change the object's attributes, graphics will change
  4. Not suitable for gaming applications

Canvas

  Canvas is to draw 2D graphics using JavaScript, HTML 5 is the new element.
Canvas Features

  1. Drawing a bitmap, the image will be distorted enlarge
  2. It does not support event handlers
  3. The image can be saved to .png or .jpg format
  4. Suitable for gaming applications

D3 Although there is no express provision must be drawing in SVG,
but D3 offers many SVG graphics generators, which are the only support SVG.
Therefore, it is recommended to use SVG canvas.

Code

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>The Fifth</title>
</head>
<script src="../../../JS/d3.min.js"></script>

<body>
      <script>
      //添加一张画布
      var width = 300;
      var height = 300;
      var svg = d3.select("body")//选择页面中的body元素
      .append("svg")//添加一个svg元素
      .attr("width",width)//设定宽度
      .attr("height",height);//设定高度
      
      //导入数据
      var dataset = [20,85,10,15,39,46];
      
      var rectHeight = 25;
      svg.selectAll("rect")
         .data(dataset)
         .enter()
         .append("rect")
         .attr("x",20)
         .attr("y",function(d,i){
            return i * rectHeight; 
        }).attr("width",function(d){
            return d;
        }).attr("height",rectHeight-2)
         .attr("fill","steelblue");
        
      svg.selectAll("rect")//选择svg内所有的矩形
         .data(dataset)//绑定数组
         .enter()//指定选择集的enter部分
         .append("rect")//添加足够数量的矩形元素
         .attr("fill","steelblue");
      </script>


</body>
</html>

Here Insert Picture Description
The last run out this effect, but this is not the final results

Published 79 original articles · won praise 89 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_39141486/article/details/102768015