Javascript画布网格偏移

imvain2

我正在尝试使用画布创建网格。网格工作正常。但是我希望网格具有偏移量,以便它与右下角对齐(只需在左边和顶部增加边距)。由于某些原因,我遇到了麻烦,我不知道为什么,我可以将左边距增加得很好,而不是顶部增加。当我将其添加到顶部时,底部的行会混乱。

我正在寻找6x10的网格。如果设置top_margin为0,则可以看到网格本身的外观,只是网格位置不正确。

另外,我在画布上具有的边框仅供参考,它不是最终设计的一部分。

我确定这可能是一些简单的问题。

c = document.getElementById("canvas");

cols = 6;
rows = 10;
col_height = 30;
col_width = 60;
grid_width = col_width * cols;
grid_height = col_height * rows;

left_margin = 42;
top_margin = 20;

var context = c.getContext("2d");

for (var x = 0; x <= grid_width; x += col_width) { //vert lines
  context.moveTo(0.5 + x + left_margin, top_margin);
  context.lineTo(0.5 + x + left_margin, grid_height);
}

for (var x = 0; x <= grid_height; x += col_height) { //hor lines
  context.moveTo(left_margin, 0.5 + x + top_margin);
  context.lineTo(grid_width + left_margin, 0.5 + x + top_margin);
}

context.strokeStyle = "black";
context.stroke();
<canvas id="canvas" style="border:1px solid #000" width="405" height="400"></canvas>

奥里价格

您只需要将边距也添加到垂直线图中(与左边距相同):

context.lineTo(0.5 + x + left_margin, grid_height + top_margin);

在此处查看固定版本:

c = document.getElementById("canvas");

cols = 6;
rows = 10;
col_height = 30;
col_width = 60;
grid_width = col_width * cols;
grid_height = col_height * rows;

left_margin = 42;
top_margin = 20;

var context = c.getContext("2d");

for (var x = 0; x <= grid_width; x += col_width) { //vert lines
  context.moveTo(0.5 + x + left_margin, top_margin);
  context.lineTo(0.5 + x + left_margin, grid_height + top_margin);
}

for (var x = 0; x <= grid_height; x += col_height) { //hor lines
  context.moveTo(left_margin, 0.5 + x + top_margin);
  context.lineTo(grid_width + left_margin, 0.5 + x + top_margin);
}

context.strokeStyle = "black";
context.stroke();
<canvas id="canvas" style="border:1px solid #000" width="405" height="400"></canvas>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章