项目开发过程中,会遇到网格,网格的实现可以用d3或canvas,现在简单介绍一下canvas的实现:
1、html代码:
<canvas id='canvas' width='1800' height='800'></canvas>
2、css代码:
body {
background: #eeeeee;
margin: 0;
padding: 0;
}
#canvas {
background: #ffffff;
border: 1px solid #ccc;
box-sizing: border-box;
cursor: pointer;
}
3、js代码:
var canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
function drawGrid(color, stepx, stepy) {
context.save()
context.fillStyle = 'white';
console.log(context);
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
context.lineWidth = 0.5;
context.strokeStyle = color;
for (var i = stepx; i < context.canvas.width; i += stepx) {
context.beginPath();
context.moveTo(i, 0);
context.lineTo(i, context.canvas.height);
context.closePath();
context.stroke();
}
for (var j = stepy; j < context.canvas.height; j += stepy) {
context.beginPath();
context.moveTo(0, j);
context.lineTo(context.canvas.width, j);
context.closePath();
context.stroke();
}
context.restore();
}
drawGrid('#ccc', 20, 20);
4、效果: