D3.JS坐标轴的使用

      网络上讲解绘图的资料很多,但是,很少从工程应用的角度来讲的。作为工程应用,首先是要建立坐标系,然后才谈其他的内容。所以,本系列先从坐标系谈起。

因为多数绘图都是使用位图(canvans)的,但是这个图不能缩放,精度不好。所以,本人倾向于采用SVG——矢量图,便于缩放。基于SVG的jS框架中,以D3的功能更强大一些,所以选择了D3。


建立绘图坐标一般需要这样几个步骤:


1.首先定义绘图区域,包括长、宽,边界;根据这些内容可以计算坐标轴的长度。

2.创建SVG变量。

3.绘制绘图的边框——就是为了好看,而且能够清晰地显示出所用区域。

4.定义坐标变换,这个很重要。

5.创建坐标轴。

6.绘制坐标轴。


//这是采用jquery的ready函数

$(function () {
    testAxisA(); //这是真正的绘图函数
});


function testAxisA() {
    console.info("测试D3.js的坐标轴");

   //绘图区域定义
    var height = 300,
            width = 400,
            margin = 50,
            offset = 50,
            axisWidth = width - 2 * margin,
            axisHeight = height - 2 * margin,
            svg;

   //创建SVG
    svg = d3.select("#graphicDiv").append("svg")
            .attr("class", "axis")
            .attr("width", width)
            .attr("height", height);

    //画一个边框--外围的
    svg.append("rect")
            .attr("class", "rect")
            .attr("x", 0)
            .attr("y", 0)
            .attr("width", width)
            .attr("height", height);
    

    //里面的边框
    svg.append("rect")
            .attr("class", "rectA")
            .attr("x", margin)
            .attr("y", margin)
            .attr("width", axisWidth)
            .attr("height", axisHeight);

    //定义坐标变换
    var scaleA = d3.scale.linear().domain([0, 1000]).range([0, axisWidth]);
    var scaleB = d3.scale.linear().domain([0, 1000]).range([axisHeight, 0]); //注意,Y坐标轴的定义是有些特殊的,需要变换方向。


    //这个变量决定坐标轴绘制的时候处于什么位置,X轴 可以上上下,Y轴是左右。
    var orientA = "bottom";

   //定义坐标轴
    var axisX = d3.svg.axis()
            .scale(scaleA)
            .orient(orientA)
            .ticks(5);


    var axisY = d3.svg.axis()
            .scale(scaleB)
            .orient("left")
            .ticks(5);

    //具体的绘制,其中 第二个变量指示坐标轴的起始位置。
    svg.append("g").attr("transform", "translate(50, 250)").call(axisX);
    svg.append("g").attr("transform", "translate(50, 50)").call(axisY);
}


另外需要注意的是“样式”, 缺省的样式不好看,推荐的样式如下:


.axis path,
.axis line{
    fill: none;
    stroke: black;
    shape-rendering: crispEdges;
}


.axis text {
    font-family: sans-serif;
    font-size: 11px;
}


.rect {
    fill:rgb(125,125,125);
    stroke-width:1;
    stroke:rgb(0,0,0)
}


.rectA {
    fill:rgb(255,255,255);
    stroke-width:1;
    stroke:rgb(0,0,0)
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值