Html 在画布 HTML5 上绘制网格/表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11735856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Draw Grid / Table on Canvas HTML5
提问by Jay Mayu
I've been searching everywhere and couldn't find how to draw a Grid / Table on a HTML5 Canvas. I'm new to HTML5 and canvas.
我一直在到处搜索,但找不到如何在 HTML5 Canvas 上绘制网格/表格。我是 HTML5 和画布的新手。
I know how to draw shapes but this drawing grid is taking forever to understand.
我知道如何绘制形状,但这个绘图网格需要很长时间才能理解。
Can someone help me on this? Your time is greatly appreciated.
有人可以帮我吗?非常感谢您的时间。
回答by John Mayer
The answer is taken from here Grid drawn using a <canvas> element looking stretched
答案取自此处使用看起来被拉伸的 <canvas> 元素绘制的 Grid
Just edited it a little, hope it helps
稍微编辑了一下,希望有帮助
<html>
<head>
<script type="text/javascript" language="javascript">
// Box width
var bw = 400;
// Box height
var bh = 400;
// Padding
var p = 10;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
function drawBoard(){
for (var x = 0; x <= bw; x += 40) {
context.moveTo(0.5 + x + p, p);
context.lineTo(0.5 + x + p, bh + p);
}
for (var x = 0; x <= bh; x += 40) {
context.moveTo(p, 0.5 + x + p);
context.lineTo(bw + p, 0.5 + x + p);
}
context.strokeStyle = "black";
context.stroke();
}
drawBoard();
</script>
</head>
<body style=" background: lightblue;">
<canvas id="canvas" width="420px" height="420px" style="background: #fff; margin:20px"></canvas>
</body>
</html>
回答by fmt.Fprint
This can be also be written as:
这也可以写成:
<html>
<head>
</head>
<body style=" background: lightblue;">
<canvas id="canvas" width="420px" height="420px" style="background: #fff; magrin:20px;"></canvas>
<script type="text/javascript" language="javascript">
var bw = 400;
var bh = 400;
var p = 10;
var cw = bw + (p*2) + 1;
var ch = bh + (p*2) + 1;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
function drawBoard(){
for (var x = 0; x <= bw; x += 40) {
context.moveTo(0.5 + x + p, p);
context.lineTo(0.5 + x + p, bh + p);
}
for (var x = 0; x <= bh; x += 40) {
context.moveTo(p, 0.5 + x + p);
context.lineTo(bw + p, 0.5 + x + p);
}
context.strokeStyle = "black";
context.stroke();
}
drawBoard();
</script>
</body>
</html>