HTML5怎么绘制坐标网格,如何使用html5和(画布或svg)绘制网格

I am posting my code using canvas here on SO but I am also creating a working sample on JSFiddle here.

StackOverflow test bed

function drawGrid() {

var cnv = document.getElementById("cnv");

var gridOptions = {

minorLines: {

separation: 5,

color: '#00FF00'

},

majorLines: {

separation: 30,

color: '#FF0000'

}

};

drawGridLines(cnv, gridOptions.minorLines);

drawGridLines(cnv, gridOptions.majorLines);

return;

}

function drawGridLines(cnv, lineOptions) {

var iWidth = cnv.width;

var iHeight = cnv.height;

var ctx = cnv.getContext('2d');

ctx.strokeStyle = lineOptions.color;

ctx.strokeWidth = 1;

ctx.beginPath();

var iCount = null;

var i = null;

var x = null;

var y = null;

iCount = Math.floor(iWidth / lineOptions.separation);

for (i = 1; i <= iCount; i++) {

x = (i * lineOptions.separation);

ctx.moveTo(x, 0);

ctx.lineTo(x, iHeight);

ctx.stroke();

}

iCount = Math.floor(iHeight / lineOptions.separation);

for (i = 1; i <= iCount; i++) {

y = (i * lineOptions.separation);

ctx.moveTo(0, y);

ctx.lineTo(iWidth, y);

ctx.stroke();

}

ctx.closePath();

return;

}

Using the canvas approach you can make the grid size dynamic by changing the separation parameter.

However, if your grid size is going to be static I feel that maybe you don't need to draw the grid. Just for the sake of displaying a grid to the user you could use CSS to repeat a background image as demonstrated in the fiddle here. That will also be good on page performance.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值