效果图如下,
var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), AXIS_MARGIN = 40, //一个常量 AXIS_ORIGIN = {x:AXIS_MARGIN,y:canvas.height-AXIS_MARGIN}, //原点坐标 AXIS_TOP = AXIS_MARGIN, //纵轴端点 AXIS_RIGHT = canvas.width-AXIS_MARGIN,//横轴端点 HORIZONTAL_TICK_SPACING = 10, //横轴间距 VERTICAL_TICK_SPACING = 10, //纵轴间距 AXIS_WIDTH = AXIS_RIGHT-AXIS_ORIGIN.x, //横轴长度 AXIS_HEIGHT=AXIS_ORIGIN.y-AXIS_TOP, //纵轴长度 NUM_VERTICAL_TICKS = AXIS_HEIGHT/VERTICAL_TICK_SPACING, //纵轴标尺的数量 NUM_HORIZONTAL_TICKS = AXIS_WIDTH/HORIZONTAL_TICK_SPACING, //横轴标尺的数量 TICK_WIDTH = 10, TICKS_LINEWIDTH = 0.5, TICKS_COLOR = "navy", AXIS_LINEWIDTH = 1.0, AXIS_COLOR = "blue"; //一个函数,由于绘制网格 function drawGrid(context,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(); } } function drawAxes(){ context.save(); context.strokeStyle = AXIS_COLOR; context.lineWidth = AXIS_LINEWIDTH; drawHorizontalAxis(); drawVerticalAxis(); context.lineWidth = 0.5; context.lineWidth = TICKS_LINEWIDTH; context.strokeStyle = TICKS_COLOR; drawHorizontalAxisTicks(); drawVertialAxisTicks(); drawNumberals(); } //横坐标 function drawHorizontalAxis(){ context.beginPath(); context.moveTo(AXIS_ORIGIN.x,AXIS_ORIGIN.y); context.lineTo(AXIS_RIGHT,AXIS_ORIGIN.y); context.stroke(); } //纵坐标 function drawVerticalAxis(){ context.beginPath(); context.moveTo(AXIS_ORIGIN.x,AXIS_ORIGIN.y); context.lineTo(AXIS_ORIGIN.x,AXIS_TOP); context.stroke(); } //绘制纵坐标标尺及刻度数 function drawHorizontalAxisTicks(){ var deltaY,num=0; for (var i = 1;i<NUM_HORIZONTAL_TICKS;++i){ context.beginPath(); if(i%5===0){ deltaY = TICK_WIDTH; text(); num++; }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 text(){ context.font = "12pt Helvetica"; context.fillText(num,AXIS_ORIGIN.x +(i-6)*HORIZONTAL_TICK_SPACING,AXIS_ORIGIN.y + 3*deltaY); } } } //横坐标标尺及刻度 function drawVertialAxisTicks(){ var deltaX,num=1; for (var i=1;i<NUM_VERTICAL_TICKS;++i){ context.beginPath(); if(i % 5 === 0){ deltaX = TICK_WIDTH; text(); num++; }else{ deltaX = TICK_WIDTH/2; } context.moveTo(AXIS_ORIGIN.x - deltaX,AXIS_ORIGIN.y - i*VERTICAL_TICK_SPACING); context.lineTo(AXIS_ORIGIN.x + deltaX,AXIS_ORIGIN.y - i*VERTICAL_TICK_SPACING); context.stroke(); function text(){ context.font = "12pt Helvetica"; context.fillText(num,AXIS_ORIGIN.x - 3*deltaX,AXIS_ORIGIN.y - i*VERTICAL_TICK_SPACING); } } } drawGrid(context,"lightgray",10,10); drawAxes();
JavaScript代码
时间: 2024-12-29 11:19:52