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>

效果

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值