如何使用 HTML5 和画布或 SVG 绘制网格 [英] How to draw grid using HTML5 and canvas or SVG

查看:43
本文介绍了如何使用 HTML5 和画布或 SVG 绘制网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

这篇关于如何使用 HTML5 和画布或 SVG 绘制网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆