2.8.3_坐标轴的绘制
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>坐标轴的绘制</title>
<style>
body{
background: #000000;
}
#canvas{
background: #fff;
}
</style>
</head>
<body>
<canvas id="canvas" width="1100" height="600"></canvas>
</body>
<script>
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
AXIS_MARGIN = 40,
AXIS_ORIGIN = { x:AXIS_MARGIN ,y:canvas.height-AXIS_MARGIN},
AXIS_TOP_Y = AXIS_MARGIN,
AXIS_RIGHT_X = canvas.width-AXIS_MARGIN,
HORIZONTAL_TICK_SPACING = 10,
VERTIVAL_TICK_SPACING = 10,
AXIS_WIDTH = AXIS_RIGHT_X - AXIS_ORIGIN.x,
AXIS_HEIGHT= AXIS_ORIGIN.y-AXIS_TOP_Y,
NUM_VERTICAL_TICKS = AXIS_HEIGHT/VERTIVAL_TICK_SPACING,
NUM_HORIZONTAL_TICKS = AXIS_WIDTH/HORIZONTAL_TICK_SPACING,
TICK_WIDTH = 10,
TICK_LINEWIDTH = 0.5,
TICK_COLOR = 'navy',
AXIS_LINEWIDTH = 1.0,
AXIS_COLOR = 'blue';
drawGrid('lightgray',10,10);
drawAxis();
function drawAxis(){
context.save();
context.strokeStyle = AXIS_COLOR;
context.lineWidth = AXIS_LINEWIDTH;
drawHorizontalAxis();
drawVerticalAxis();
context.strokeStyle = TICK_COLOR;
context.LINE_WIDTH = TICK_LINEWIDTH;
drawVerticalAxisTick();
drawHorizontalAxisTick();
context.restore();
}
function drawHorizontalAxisTick(){
var deltaY;
for(var i=0;i<NUM_HORIZONTAL_TICKS;i++){
context.beginPath();
if(i%5===0){
deltaY = TICK_WIDTH;
}else{
deltaY = TICK_WIDTH/2;
}
context.moveTo(AXIS_ORIGIN.x+i*HORIZONTAL_TICK_SPACING,AXIS_ORIGIN.y+deltaY);
context.lineTo(AXIS_ORIGIN.x+i*HORIZONTAL_TICK_SPACING,AXIS_ORIGIN.y-deltaY);
context.stroke();
}
}
function drawVerticalAxisTick(){
var deltaX;
for(var i = 0;i<NUM_VERTICAL_TICKS;++i){
context.beginPath();
if(i%5===0){
deltaX = TICK_WIDTH;
}else{
deltaX = TICK_WIDTH/2;
}
context.moveTo(AXIS_ORIGIN.x-deltaX,AXIS_ORIGIN.y-i*VERTIVAL_TICK_SPACING);
context.lineTo(AXIS_ORIGIN.x+deltaX,AXIS_ORIGIN.y-i*VERTIVAL_TICK_SPACING);
context.stroke();
}
}
function drawHorizontalAxis(){
context.beginPath();
context.moveTo(AXIS_ORIGIN.x,AXIS_ORIGIN.y);
context.lineTo(AXIS_RIGHT_X,AXIS_ORIGIN.y);
context.stroke();
}
function drawVerticalAxis(){
context.beginPath();
context.moveTo(AXIS_ORIGIN.x,AXIS_ORIGIN.y);
context.lineTo(AXIS_TOP_Y,AXIS_ORIGIN.x);
context.stroke();
}
function drawGrid(color,stepX,stepY){
context.strokeStyle =color;
context.lineWidth = 0.5;
for(var i=stepX+0.5;i<context.canvas.width;i+=stepX){
context.beginPath();
context.moveTo(i,0);
context.lineTo(i,context.canvas.height);
context.stroke();
}
for(var i=stepY+0.5;i<context.canvas.height;i+=stepY){
context.beginPath();
context.moveTo(0,i);
context.lineTo(context.canvas.width,i);
context.stroke();
}
}
</script>
</html>