There are three ways to create dotted lines in HTML: CSS border-style property: Use dashed or dotted values to create dotted lines. SVG elements: Use the stroke-dasharray attribute to create a dashed line, controlling the length and spacing of dashes or dots. Canvas element: Use the setLineDash() method to create dashed lines, providing more flexibility.
How to create dotted lines in HTML
Using CSS border-style
Properties
This is the most common way to create dashed lines using HTML and CSS. The border-style
property accepts the following values to create a dashed line:
dashed
: Creates a dashed line consisting of dashes. dotted
: Creates a dotted line composed of dots. Example:
<code class="html"><p style="border: 1px dashed black;">虚线段落</p></code>
Using SVG elements
SVG elements (such as <line>
and <path>
) can be used to create dashed lines using the stroke-dasharray
property. stroke-dasharray
Accepts an array of values representing the length and spacing of dashes or dots for a dashed line.
Example:
<code class="html"><svg width="100" height="100"> <line x1="0" y1="0" x2="100" y2="100" stroke-dasharray="5 10" /> </svg></code>
Using the Canvas element
The Canvas element uses the JavaScript API to create dashed lines. The getContext()
method returns a canvas context object that provides the setLineDash()
method.
Example:
<code class="html"><canvas id="canvas" width="100" height="100"></canvas> <script> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.setLineDash([5, 10]); ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(100, 100); ctx.stroke(); </script></code>
Choose a method
Selecting the most appropriate dash line creation method depends on your specific needs. The CSS border-style
property is the simplest method, but the SVG and Canvas elements offer more flexibility.
The above is the detailed content of How to make dotted lines in html. For more information, please follow other related articles on the PHP Chinese website!