search
HomeWeb Front-endH5 TutorialThe role of svg path: How to use svg path in web development

This article introduces you to the article about the role of SVG Path in web development. It has a good reference value. I hope it can help friends in need.

SVG is a vector graphics representation. One of its powerful features is that the path tag can represent any vector shape. By making good use of this path, you can create many effects that traditional HTML/CSS cannot. Here are a few examples.

1. Make path animation

I added this implementation in the article "SVG Navigation Underline Cursor Following Effect". The final effect is like this:

The role of svg path: How to use svg path in web development

The implementation code is as follows:

The role of svg path: How to use svg path in web development

Using animateMotion combined with path to create animations, specific instructions can be found above.

2. To achieve irregular-shaped clicks

As shown in the figure below, you need to achieve the effect of entering which continent you click on. For example, clicking on Africa will enter Africa:

The role of svg path: How to use svg path in web development

We can use div to define a frame on top of Africa, but using div can only be a regular square shape. There is no way to enter when you click on the African continent, but the continent The outline is irregular, so traditional HTML cannot solve this problem. However, this problem can be solved with SVG path. Method 1 is to listen to the click event of the path, as shown in the following figure:

The role of svg path: How to use svg path in web development

Because this outline can be obtained from the UI, They are usually drawn using vector software such as AI/PS. Just ask them to import an SVG for you.

Method 2 is to adjust the isPointInFill API of SVG to determine whether the clicked point is in the fill area of ​​Path. This can also be implemented, but it is more troublesome than method 1 because it also needs to adjust the position of the mouse. Convert to position of svg view.

3. Interaction of dragging along the path

The animation along the path at the first point is an automatic process. Is there a way for the user to drag it by himself to achieve the following effect:

The role of svg path: How to use svg path in web development

This kind of scenario requires percentage control such as volume control. You can first use an SVG online tool to draw a graphic like this:

The role of svg path: How to use svg path in web development

Then you can get the SVG code:

<svg class="volumn-controller" width="580" height="400" xmlns="http://www.w3.org/2000/svg">
    <path class="volumn-path" stroke="#000" d="m100,247c93,-128 284,-129 388,6" opacity="0.5" stroke-width="1" fill="#fff"/>
    <circle class="drag-button" r="12" cy="247" cx="100" stroke-width="1" stroke="#000" fill="#fff"/>
 </g>
</svg>

The key thing here is The d attribute in the path tag, d is the abbreviation of data, defines the shape of this path. Many attributes can be used to control the change of the shape, as shown in the following figure:

The role of svg path: How to use svg path in web development

In order to realize this interaction, it is necessary to dynamically change the center position (cx, cy) of the circle to the corresponding place on the path. SVG does not directly provide related APIs, but it provides an API that can be used indirectly called getPointAtLength, passing a length parameter, as shown in the following code:

let volumnPath = document.querySelector(&#39;.volumn-path&#39;);
// 输出path在长度为100的位置的点坐标
console.log(volumnPath.getPointAtLength(100));
// 输出当前path的总长度
console.log(volumnPath.getTotalLength());

Console output:

The role of svg path: How to use svg path in web development

Change the cx/cy of circle to the x/y coordinates above, and the circle will go to the corresponding position:

The role of svg path: How to use svg path in web development

Here The problem is that the length parameter passed by this API is relative to the length of the curve, but the position of the mouse movement is linear, and there is no way to directly know how far the current mouse is from the starting position on the curve.

So we need to do some calculations. In this scene, we can just take the corresponding position of the x-coordinate of the mouse on the curve, as shown in the following figure:

The role of svg path: How to use svg path in web development

Here you have an idea. You can calculate the coordinates of every pixel on this path and store it in an array. Since the x coordinate is known when the mouse moves, you can check the y coordinate of the corresponding x coordinate in this array to get the desired center position of the circle.

So calculate it first and save it to an array:

let $volumnController = document.querySelector(&#39;.volumn-controller&#39;),
    $volumnPath = $volumnController.querySelector(&#39;.volumn-path&#39;);
// 得到当前路径的总长度
let pathTotalLength = $volumnPath.getTotalLength() >> 0;
let points = [];
// 起始位置为长度为0的位置
let startX = Math.round($volumnPath.getPointAtLength(0).x);
// 每隔一个像素距离就保存一下路径上点的坐标
for (let i = 0; i < pathTotalLength; i++) {
    let p = $volumnPath.getPointAtLength(i);
    // 保存的坐标用四舍五入,可以平衡误差
    points[Math.round(p.x) - startX] = Math.round(p.y);
}

Here a p0ints array is used to save it. Its index index is the x coordinate and the value is the y coordinate. In this example, the total length is 451.5px, and the resulting points array length is 388. You can save coordinates every 0.5px, but in this example 1px is enough.

然后监听鼠标事件,得到x坐标,查询y坐标,动态地改变circle的圆心位置,如下代码所示:

let $dragButton = $volumnController.querySelector(&#39;.drag-button&#39;),
    // 得到起始位置相对当前视窗的位置,相当于jQuery.fn.offset
    dragButtonPos = $dragButton.getBoundingClientRect();
function movePoint (event) {
    // 当前鼠标的位置减去圆心起始位置就得到移位偏差,12是半径值,这里先直接写死
    let diffX = event.clientX - Math.round(dragButtonPos.left + 12);
    // 需要做个边界判断
    diffX < 0 && (diffX = 0);
    diffX >= points.length && (diffX = points.length - 1);
    // startX是在上面的代码得到的长度为0的位置
    $dragButton.setAttribute(&#39;cx&#39;, diffX + startX);
    // 使用points数组得到y坐标
    $dragButton.setAttribute(&#39;cy&#39;, points[diffX]);
}
$dragButton.addEventListener(&#39;mousedown&#39;, function (event) {
    document.addEventListener(&#39;mousemove&#39;, movePoint);
});
document.addEventListener(&#39;mouseup&#39;, function () {
    document.removeEventListener(&#39;mousemove&#39;, movePoint);
});    					

这个实现的代码也是比较简单,需要注意的地方是起始位置的选取,这里有两个坐标系,一个是相对页面的视窗的,它的原点(0, 0)坐标点是当前页面可视区域(client)的左上角,第二个坐标系是SVG的坐标系,它的原点(0, 0)位置是SVG画布的左上角,如下图所示:

1The role of svg path: How to use svg path in web development

鼠标的位置是相对于视图client的,所以需要得到圆圈在client的位置,可以通过原生的getBoundingClient获取,然后用鼠标的clientX减掉圆圈的clientX就得到正确的位移偏差diff了,这个diff值加上圆圏的在svg坐标的起始位置就能得到svg里的x坐标了,然后去查一下points数组就能得到y坐标,然后去设置circle的cx/cy值。

这个的实现已经算是十分简单的,大概30行代码。需要注意的是如果svg缩放了,那么坐标也要相应比例地改一下。所以最好是不要缩放,1:1显示就简单多了。

如果要显示具体的音量值呢?这个也好办,只需要在第一步保存点坐标的时候把在路径上的长度也保存下来就好了,最后效果如下:

The role of svg path: How to use svg path in web development

如果路径比较复杂怎么办呢,一个x坐标可能会对应两个点,如下图所示:

1The role of svg path: How to use svg path in web development

这个也是有办法的,计算的方法类似,也是需要把路径上所有每隔1px的点坐标都取出来,然后计算一下鼠标的位置距离哪个点的坐标最接近,然后就取那个点就好了。当然在判断哪个点最优时,算法需要优化,不能直接一个for循环,具体可见这个codepen。

4. 路径的变形动画

路径结合关键帧可以做出一些有趣的效果,如这个codepen的示例:

The role of svg path: How to use svg path in web development

它的实现是hover的时候改变path的d值,然后做d的transition动画,如下代码:

<svg viewBox="0 0 10 10" class="svg-1">
  <path d="M2,2 L8,8" />
</svg>
<style>
.svg-1:hover path {
  d: path("M8,2 L2,8");
}
path {
    transition: d 0.5s linear;
}
</style>

这种变形过渡动画是有条件的,就是它的路径数据格式是要一致的,有多少个M/L/C属性都要保持一致,否则无法做变形动画。

5. 结合clip-path做遮罩效果

使用CSS通常只能用border-radius做一些圆角的遮罩,即用border-radius结合overflow: hidden实现,但是使用clip-path + svg的路径能够做出任意形状遮罩,如下做一个心形的:

The role of svg path: How to use svg path in web development

如下代码所示:

<div style="width:200px;height:200px">
    <img src="/static/imghwm/default1.png"  data-src="photo.png"  class="lazy"   alt   style="max-width:90%">
</div>
<style>
img {
    clip-path: url("#heart");
}
</style>

style里面的id: #heart是指向了一个SVG的的clipPath,如下所示:

<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0">
    <clipPath id="heart" clipPathUnits="objectBoundingBox">
        <path transform="scale(0.0081967, 0.0101010)" d="m61.18795,24.08746c24.91828,-57.29309 122.5489,0 0,73.66254c-122.5489,-73.66254 -24.91828,-130.95562 0,-73.66254z"/>
    </clipPath>
</svg>   					

为了让这个path刚好能撑起div容器宽度的100%,需要设置:

clipPathUnits="objectBoundingBox"

这样会导致d属性里面的单位变成比例的0到1,所以需要把它缩小一下,原本的width是122,height是99,需要需要scale的值为(1 / 122, 1 / 99)。这样就达到100%占满的目的,如果一开始d属性坐标比例就是0到1,就不用这么搞了。

另外clip-path使用svg的path不支持变形动画。

本篇介绍了使用svg路径path做的几种效果:做一个路径动画、不规则形状的点击、沿着路径拖拽、路径的变形动画以及和clip-path做一些遮罩效果。可以说svg的path效果还是很强大的,当你有些效果用html/css无法实现的时候,不妨往svg的方向思考。

相关推荐:

如何使用Chrome控制台进行3D模型编辑的实现(代码)

在canvas上实现元素图片镜像翻转动画效果的方法

The above is the detailed content of The role of svg path: How to use svg path in web development. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools