效果:
源码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>坐标系绘制</title> </head> <body> <canvas id="canvas"></canvas> <script> (function () { //canvas布局 var canvas = document.getElementById("canvas"); canvas.width = 600; canvas.height = 600; canvas.style.border = "1px solid red"; //获取上下文 var ctx = canvas.getContext("2d"); //绘制坐标轴 var x0 = 100,y0 = 500;// xy轴原点 var maxX = 500,maxY = 100; var lineWidth = 10;//箭头宽度 //x轴 ctx.beginPath(); ctx.moveTo(x0,y0); ctx.lineTo(maxX,y0); ctx.lineTo(maxX-lineWidth,y0+lineWidth); ctx.moveTo(maxX,y0); ctx.lineTo(maxX-lineWidth,y0-lineWidth); ctx.stroke(); //y轴 ctx.beginPath(); ctx.moveTo(x0,y0); ctx.lineTo(x0,maxY); ctx.lineTo(x0-lineWidth,maxY+lineWidth); ctx.lineTo(x0,maxY); ctx.lineTo(x0+lineWidth,maxY+lineWidth); ctx.stroke(); //折线 var data = [.5,.4,.6,.8,.7,.9,.3]; var xWidht = 400/(data.length+1);//x轴间距 ctx.beginPath(); for(var i = 0;i<data.length;i++){ ctx.lineTo(100+xWidht*(i+1),500-400*data[i]); } ctx.strokeStyle = 'blue'; ctx.stroke(); }()) </script> </body> </html>