D3的快速入门

D3 数据可视化

引入文件,下载到本地或者使用cdn

<script src='source/d3.js'></script>

D3 的选择器

具体的不说了,文档都有,用到什么讲什么吧
在这里插入图片描述

例子:

在svg中添加图形

    类似canvas fill填充 stroke 描边框
 <style>
        .cir{
            fill: skyblue;
            stroke:black;
            stroke-width:3px;

        }
        .rect{
            fill:yellow;
            stroke:blue;
            stroke-width:2px;
        }
</style>


<script src='source/d3.js'></script>
<script>
    var body = d3.select('body');
    body.append('h1')
        .text('hello');
    body.append('p')
        .text('d3')

    var svg = body.append('svg').attr('width',400).attr('height',400) 
    svg.append('circle')
    .attr('cx',100)// 圆心位置坐标 
    .attr('cy',200)// 
    .attr('r',80) //圆 半径
    .attr('class','cir') 

    svg.append('rect')
    .attr('x',200) //顶点坐标
    .attr('y',120) 
    .attr('height',200) //宽高
    .attr('width',150)	
    .attr('class','rect') //设置class
</script>

动态设置图形大小
 我们通过D3的 selection.data() 方法来将 data 绑定到 DOM 元素。因此,一个绑定过程的必要条件既是:data 和 DOM目标元素(没有目标元素,你就没法呈现数据,没有数据,你的dom也就没法展示)。

	// 数据与dom 之间的关系
	 var dataset = [30, 40, 50, 60, 70, 80]
	 var update=p.data(dataset);
     enter = update.enter() //多余的数据  需要添加dom
        .append('p')
         .text((d) => d)
     console.log(enter)
	
     exit = enter.exit()
         .remove()         //多余的dom
     console.log(exit)
 <style>
     .myRect {
         fill: greenyellow;
     }
</style>

<script src="source/d3.js"></script>
<script>
	var body = d3.select('body');// 类似JQ的选择器($('.类名||#id名||元素名'))
	var svg = body.append('svg') // d3 可以链式调用
        .attr('width', width)		// 设置svg 的宽高
        .attr('height', height)
    var rect = svg.selectAll('.myRect')
        .data(dataset)
        .enter()
        .append('rect')   //每一次的数据,都添加一个rect 矩形
        .attr('class', 'myRect')//设置相同的class名
        .attr('x', function (d, i) { // 需要 横向展示  有间隔
            return 20 + 35 * i //返回值为x轴的坐标值
        })
        .attr('y', function (d, i) { 
            return height - 80 - d	//返回值为rect根据数据实际展示的高度
        })
        .attr('width', 30)
        .attr('height', function (d3) {
            return d3
        })
</script>

效果

在这里插入图片描述
未完待续。。

发布了2 篇原创文章 · 获赞 2 · 访问量 97

猜你喜欢

转载自blog.csdn.net/qq_44393166/article/details/105097503
D3