简体   繁体   English

如何为 SVG 中风设置动画以充当仪表?

[英]How do I animate SVG stroke to act as a gauge?

I have this code set up:我设置了以下代码:

 .gauge { stroke-dasharray: 1000; stroke-dashoffset: 500; animation: dash 5s linear alternate; } @keyframes dash { from { stroke-dashoffset: 0; } to { stroke-dashoffset: 1000; } }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href="dist/style.css"> <title>Gauge</title> </head> <body> <div class="gauge"> <svg width="500" height="500" fill="white" stroke="red" stroke-width="25" stroke-linecap="round"> <circle cx="200" cy="200" r="100"/> </svg> </div> </body> </html>

What I'd like to do is to turn it into a gauge as this (forget about the color & All): enter image description here我想做的就是把它变成这样的量规(忘记颜色和全部):在此处输入图像描述

I'm having hard trouble understanding the dasharray & dashoffset commands in order to transform it into what I need...can anyone help with that?我很难理解 dasharray 和 dashoffset 命令,以便将其转换为我需要的...有人可以帮忙吗?

Animating either stroke-dashoffset or stroke-dasharray depends partly on the use case.动画stroke-dashoffsetstroke-dasharray部分取决于用例。 Here I find it easier to 1) rotate the circle with transform/rotate and 2) animate the stroke-dasharray .在这里,我发现 1) 使用 transform/rotate 旋转圆圈和 2) 为stroke-dasharray设置动画更容易。

A prerequisite is setting the pathLength attribute.先决条件是设置 pathLength 属性。 Setting it on a <circle> will control the the length of a full circle.将其设置在<circle>上将控制一个完整圆的长度。 In this case it looks more or less like the gauge is 2/3 of a circle.在这种情况下,它看起来或多或少像仪表是一个圆的 2/3。 So, it makes sense for the full circle to be 150 and 2/3 is then 100.因此,整圈为 150 且 2/3 为 100 是有意义的。

Now the length of the gauge can be controlled by the first value in the stroke-dasharray .现在,仪表的长度可以由stroke-dasharray中的第一个值控制。 The second value should just grater than 100 -- it is the length of the space between the line in the array.第二个值应该大于 100——它是数组中行之间的空间长度。

 .gauge { stroke-dasharray: 100 150; animation: dash 5s linear alternate; } @keyframes dash { from { stroke-dasharray: 100 150; } to { stroke-dasharray: 0 150; } }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href="dist/style.css"> <title>Gauge</title> </head> <body> <div class="gauge"> <svg width="500" height="500" fill="white" stroke="red" stroke-width="25" stroke-linecap="round"> <circle transform="rotate(150 200 200)" cx="200" cy="200" r="100" pathLength="150"/> </svg> </div> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM