如何使用 HTML5 和画布或 SVG 绘制网格

2022-01-17 00:00:00 svg html html5-canvas

我想画一个如图所示的网格,但我完全不知道从哪里开始.

I want to draw a grid as shown in the image but I totally don't have any idea where to begin.

我应该使用 SVG 还是应该使用带有 HTML5 的 Canvas 以及如何在其上绘图?

Should I use SVG or should I use Canvas with HTML5 and how do I draw on it?

我希望此网格在其上绘制矩形、圆形或其他图表,我将计算该图表的面积,就像正方形的面积一样.

I want this grid to draw rectangle, circle or other diagrams on it and I will calculate the area of that diagram like area of a square.

推荐答案

SVG 可以很好地使用模式:

SVG can do this nicely using patterns:

<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <pattern id="smallGrid" width="8" height="8" patternUnits="userSpaceOnUse">
      <path d="M 8 0 L 0 0 0 8" fill="none" stroke="gray" stroke-width="0.5"/>
    </pattern>
    <pattern id="grid" width="80" height="80" patternUnits="userSpaceOnUse">
      <rect width="80" height="80" fill="url(#smallGrid)"/>
      <path d="M 80 0 L 0 0 0 80" fill="none" stroke="gray" stroke-width="1"/>
    </pattern>
  </defs>
      
  <rect width="100%" height="100%" fill="url(#grid)" />
</svg>

我将 widthheight 设置为 100%,因此您可以定义使用时的实际宽度和高度,无论是对于内联 SVG:

I set width and height to 100%, so you can define the actual width and height on use, either for inline SVG:

<div style="width:400px;height:300px">
  <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
    <defs>
      <pattern id="smallGrid" width="8" height="8" patternUnits="userSpaceOnUse">
        <path d="M 8 0 L 0 0 0 8" fill="none" stroke="gray" stroke-width="0.5"/>
      </pattern>
      <pattern id="grid" width="80" height="80" patternUnits="userSpaceOnUse">
        <rect width="80" height="80" fill="url(#smallGrid)"/>
        <path d="M 80 0 L 0 0 0 80" fill="none" stroke="gray" stroke-width="1"/>
      </pattern>
    </defs>
        
    <rect width="100%" height="100%" fill="url(#grid)" />
  </svg>
</div>

或一个 <img> 元素:

<img src="https://svgshare.com/i/9Eo.svg" width="700" height="200"/>

结果:

<img src="https://svgshare.com/i/9Eo.svg" width="241" height="401"/>

结果

请注意,对于这个特定的网格,如果您想要网格,您必须使用 nx 80 + 1 形式的宽度和高度(n 是任何整数)以粗笔画开始和结束.

Note that for this particular grid you have to use widths and heights of the form n x 80 + 1 (with n being any integer) if you want the grid to start and end with a thick stroke.

相关文章