龙空技术网

SVG 绘制直线

MAO大侠 107

前言:

今天各位老铁们对“css构建直线”大体比较关心,你们都想要学习一些“css构建直线”的相关内容。那么小编也在网摘上搜集了一些对于“css构建直线””的相关知识,希望同学们能喜欢,大家快快来学习一下吧!

本节我们来学习如何在 SVG 中绘制直线,要绘制直线可以使用 <line> 元素来实现。

如何绘制直线

我们可以使用 <line> 元素在 SVG 图像内部来绘制线条,要绘制直线,首先要确定直线起点与重点的位置。可以通过元素中的属性来绘制水平直线、垂直直线、斜角直线等。

绘制直线时需要用到四个属性,如下所示:

x1: 定义线条在 x 轴的起始坐标。x2: 定义线条在 x 轴的结束坐标。y1: 定义线条在 y 轴的开始坐标。y2: 定义线条在 y 轴的结束坐标。

示例:

例如绘制四条不同颜色的线条:

<!DOCTYPE html><html>    <head>        <meta charset="utf-8">        <title>SVG学习(9xkd.com)</title>        <link rel="styleSheet" type="text/css" href="./style.css">    </head>    <body>        <svg width="300" height="300">            <line x1="50" y1="10" x2="200" y2="10" style="stroke:#fa9668; stroke-width:3px; "></line>            <line x1="50" y1="30" x2="200" y2="70" style="stroke:#64f590; stroke-width:3px; "></line>            <line x1="50" y1="50" x2="200" y2="150" style="stroke:#c17af0; stroke-width:3px; "></line>            <line x1="50" y1="70" x2="50" y2="200" style="stroke:#f07abf; stroke-width:3px; "></line>        </svg>    </body></html>   

在浏览器中的演示效果:

在绘制这些直线时,是通过两个点来绘制的,我们可以通过控制起始点的坐标和结束点的坐标控制线条的位置。使用 stroke 属性设置线条的颜色,stroke-width 属性设置线条的宽度。

使用多条直线组成一个矩形

我们可以通过绘制多条直线来组成一个矩形。

示例:

<!DOCTYPE html><html>    <head>        <meta charset="utf-8">        <title>SVG学习(9xkd.com)</title>        <link rel="styleSheet" type="text/css" href="./style.css">    </head>    <body>        <svg width="300" height="300">            <line x1="50" y1="10" x2="200" y2="10" style="stroke:#fa9668; stroke-width:3px; "></line>            <line x1="200" y1="10" x2="200" y2="200" style="stroke:#64f590; stroke-width:3px; "></line>            <line x1="200" y1="200" x2="50" y2="200" style="stroke:#c17af0; stroke-width:3px; "></line>            <line x1="50" y1="200" x2="50" y2="10" style="stroke:#f07abf; stroke-width:3px; "></line>        </svg>    </body></html>   

在浏览器中的演示效果:

标签: #css构建直线