How to draw grid using HTML5 and canvas or SVG(如何使用 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 还是应该使用带有 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>
我将 width
和 height
设置为 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 绘制网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 HTML5 和画布或 SVG 绘制网格


基础教程推荐
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01