imvain2
imvain2

Reputation: 15847

Javascript Canvas Grid Offsets

I'm trying to create a grid using canvas. The grid is working fine. But I would like the grid to have an offset so it aligns to the bottom right (just adding margin to the left and top). For some reason, I'm having trouble and I can't figure out why, I can get the left margin added fine just not the top. When I add it to the top, the bottom rows mess up.

I'm looking for a 6x10 grid. If you set top_margin to 0, you can see how the grid itself should look, its just not in the right location.

Also the border I have on canvas is just there for visual reference, its not part of the final design.

I'm sure its probably something simple that is the problem.

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>

Upvotes: 1

Views: 55

Answers (1)

Ori Price
Ori Price

Reputation: 4201

You just need to add your margin to your vertical lines drawing as well (same as you did with the left margin):

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

See Fixed Version here:

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>

Upvotes: 1

Related Questions