简体   繁体   中英

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM