path.getTotalLength()返回错误的值

时间:2016-10-28 02:56:02

标签: javascript html css svg

我最近一直在玩svg动画。更具体地说,我只是试图获得线条绘制自己的效果。到目前为止它是有道理的,但我遇到了一些问题。

在复杂形状上,getTotalLength()返回的值似乎是错误的。它通常表示路径比它长。

在此示例中,路径(在我的屏幕上)大约是报告的一半: https://jsfiddle.net/36u7Lztv/2/

HTML:

<svg  width="1023.5735" height="339.87985" viewBox="0 0 1023.5737 339.87985" >
    <g transform="translate(-2.8122176,-453.90997)" >
       <path id='lens_right' class='lens'
            d="m 316.71289,297.36523 c -0.11819,0.016 -0.24013,0.0412 -0.35742,0.0547 0.566,0.18666 1.12735,0.23429 1.68164,0.16602 -0.44147,-0.0734 -0.88314,-0.14373 -1.32422,-0.22072 z M 173.86328,445.8125 C 115.7806,445.9007 56.06865,450.63489 1.0585938,461.85352 l 1.9397734,72.7392 c -1e-7,0 16.2532068,18.31933 17.1835938,36.63281 7.809399,154.2024 84.019299,222.56445 230.091789,222.56445 117.58238,0 160.41001,-31.53414 192.45313,-124.72461 34.65112,-100.76402 54.39723,-115.49536 72.95078,-115.49536 18.55362,0 36.33586,14.73134 70.98281,115.49536 32.05142,93.19047 74.8706,124.72461 192.45703,124.72461 146.07668,0 222.2826,-68.36205 230.0918,-222.56445 0.9262,-18.31554 17.1719,-36.63477 17.1719,-36.63477 l 0,-73.26953 C 970.87866,455.60266 908.72901,458.90001 850.64648,458.8125 775.96903,458.69998 707.53291,462.34077 650.69355,469.17304 539.89171,481.65973 487.5315,480.99999 376.36719,464.59766 320.52651,453.26539 248.54104,445.69916 173.86328,445.8125 Z"
            transform="matrix(1.0086962,0,0,1,-8.9208996,-1.22e-4)"
            />
    </g>
</svg>

CSS:

body {
  background: teal;
}

svg {
  width: 50%;
}

svg path {
  fill: #000000;
  fill-opacity: 1;
  stroke: #ffffff;
  stroke-width: 1;
  vector-effect: non-scaling-stroke;
  transition: all 3s linear;
}

使用Javascript:

var path1 = document.getElementById('lens_right');
var path1Len = path1.getTotalLength();

var strokeLen = path1Len; // easier troubleshooting

path1.style.strokeDasharray = strokeLen;
path1.style.strokeDashoffset = -strokeLen;

// add/remove border on hover
document.body.onmouseover = function() {
    path1.style.strokeDashoffset = '0';
}

document.body.onmouseout = function() {
    path1.style.strokeDashoffset = -strokeLen;
}

在边界开始绘制之前你会注意到一点延迟。

使用strokeLen的值(例如,将path1Len除以2)可以使线的起点更接近正确的位置,但在不同的设备上硬编码可能不准确和决议。

无论浏览器如何,我都得到相同的结果。几年前我发现了一些旧的Firefox错误报告涉及同样的问题,但他们说这是固定的,并提到它不是Chrome的问题。

有没有人知道修复此问题?

1 个答案:

答案 0 :(得分:3)

您的问题是由您使用的原因造成的:

vector-effect: non-scaling-stroke;

使用这意味着您正在转换路径,但是笔划(因此是dasharray)不是。

如果删除vector-effect并使stroke-width更大(因此可见),则会获得更好的结果。虽然你现在还需要修复其他一些东西。

https://jsfiddle.net/36u7Lztv/4/