网络上讲解绘图的资料很多,但是,很少从工程应用的角度来讲的。作为工程应用,首先是要建立坐标系,然后才谈其他的内容。所以,本系列先从坐标系谈起。
因为多数绘图都是使用位图(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)
}