Kyl*_*-St 6 html javascript svg svg-animate
我有一个灰色虚线的SVG.我想要做的是在绿色SVG虚线上叠加,并将灰色动画显示绿色.Sorta就像一个从右到左移动的仪表.
我看到了如何制作虚线的这个例子:
并且能够做到但我的线已经破灭了.
我最终这样做了:
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 666.9 123.8" enable-background="new 0 0 666.9 123.8" xml:space="preserve">
<path opacity="0.4" stroke-width="3" fill="none" stroke="#66CD00" stroke-linecap="round" stroke-miterlimit="5" stroke-dasharray="1,6" d="
M656.2,118.5c0,0-320.4-251-645.9-0.7" />
<path id="top" opacity="0.4" fill="none" stroke="#AEAEAE" stroke-linecap="round" stroke-miterlimit="5" stroke-dasharray="1,6" d="
M656.2,118.5c0,0-320.4-251-645.9-0.7"/>
</svg>
var path = document.querySelector('#top');
var length = path.getTotalLength();
// Clear any previous transition
path.style.transition = path.style.WebkitTransition =
'none';
// Set up the starting positions
path.style.strokeDasharray = 1 + ' ' + 6;
path.style.strokeDashoffset = length;
// Trigger a layout so styles are calculated & the browser
// picks up the starting position before animating
path.getBoundingClientRect();
// Define our transition
path.style.transition = path.style.WebkitTransition =
'stroke-dashoffset 20s linear';
// Go!
path.style.strokeDashoffset = '0';
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/ps5yLyab/
如何叠加两条虚线并为灰色设置动画?
您可以使用剪辑路径来完成此操作。
首先我们向 SVG 添加一个 ClipPath。
<defs>
<clipPath id="myclip">
<rect id="cliprect" x="100%" y="0%" width="100%" height="100%"/>
</clipPath>
</defs>
Run Code Online (Sandbox Code Playgroud)
该剪辑路径的大小与 SVG 的大小相同(宽度和高度 100%),并从 SVG 最右侧的 x 位置开始(100%)。所以一开始它并没有透露任何东西。
然后每 10mS 我们将它的 x 坐标减少 1%(即 100% -> 99% -> 98% 等)。直到达到零。
var cliprect = document.getElementById("cliprect");
var offsetX = 100;
var speed = 10;
function clipAdjust()
{
cliprect.setAttribute("x", offsetX+"%");
offsetX -= 1;
if (offsetX >= 0) {
window.setTimeout(clipAdjust, speed);
}
}
window.setTimeout(clipAdjust, speed);
Run Code Online (Sandbox Code Playgroud)
工作演示如下:
<defs>
<clipPath id="myclip">
<rect id="cliprect" x="100%" y="0%" width="100%" height="100%"/>
</clipPath>
</defs>
Run Code Online (Sandbox Code Playgroud)
var cliprect = document.getElementById("cliprect");
var offsetX = 100;
var speed = 10;
function clipAdjust()
{
cliprect.setAttribute("x", offsetX+"%");
offsetX -= 1;
if (offsetX >= 0) {
window.setTimeout(clipAdjust, speed);
}
}
window.setTimeout(clipAdjust, speed);
Run Code Online (Sandbox Code Playgroud)