Canvas---折线图---绘制网格
折线图---绘制网格
布置好canvas
<canvas width="600" height="400"></canvas>
<style> canvas { border: 1px solid #ccc; } </style>
var myCanvas = document.querySelector('canvas');
var ctx = myCanvas.getContext('2d');
画网格大小
var gridSize = 10;
画多少条X轴方向的线,横线的条数取决于画布高度,同理纵线条数=>画布宽度
var canvasHeight = ctx.canvas.height; var canvasWidth = ctx.canvas.width; console.log(ctx.canvas.height); console.log(ctx.canvas.width);
遍历的形式去画
X轴
var xLineTotal = Math.floor(canvasHeight / gridSize); for (var i = 0; i <= xLineTotal; i++) { ctx.beginPath(); ctx.moveTo(0, i * gridSize - 0.5); //canvasHeight=xlineTotal(也就是i)*gridSize ctx.lineTo(canvasWidth, i * gridSize - 0.5); ctx.strokeStyle = '#eee'; ctx.stroke(); }
Y轴
var yLineTotal = Math.floor(canvasWidth / gridSize); for (var i = 0; i <= yLineTotal; i++) { ctx.beginPath(); ctx.moveTo(i * gridSize - 0.5, 0); ctx.lineTo(i * gridSize - 0.5, canvasHeight); ctx.strokeStyle = '#eee'; ctx.stroke(); }
你好,我是Jane,如果万幸对您有用,请帮忙点下推荐,谢谢啦~另外,咱们闪存见哦~