路径“d”属性的SVG错误

时间:2013-04-22 01:16:29

标签: javascript svg

我正在尝试使用JavaScript动态创建路径,但d属性不断提供Uncaught SyntaxError: Unexpected token ILLEGAL.

var location = document.createElementNS(svgns,"path");
    location.setAttributeNS("fill-rule","evenodd");
    location.setAttributeNS("fill","#ffffff");
    location.setAttributeNS("clip-rule","evenodd");
    location.setAttributeNS(null,"d","M57.295,27.757c-11.896,0-21.539,9.643-21.539,21.539S57.295,86.5,57.295,86.5
    s21.539-25.309,21.539-37.205S69.19,27.757,57.295,27.757z M57.295,60.039c-6.373,0-11.539-5.166-11.539-11.539
    s5.166-11.539,11.539-11.539S68.833,42.127,68.833,48.5S63.667,60.039,57.295,60.039z");

    locationBTn.appendChild(locationStroke0);
    locationBTn.appendChild(location);

    document.getElementsByTagName('svg')[0].appendChild(locationBTn);

1 个答案:

答案 0 :(得分:1)

在此处指定路径数据时要小心。换行可能会带来麻烦。

作为简化示例:

location.setAttributeNS(null,"d","M5.5,
27.2,
c11.89,
0-21.5,9.6");

不同
location.setAttributeNS(null,"d","M5.5,27.2,c11.89,0-21.5,9.6");

您有几个选择:

A)全部放在一行:

location.setAttributeNS(null,"d","M57.295,27.757c-11.896,0-21.539,9.64321.539,21.539S57.295,86.5,57.295,86.5s21.539-25.309,21.539-37.205S69.19,27.757,57.295,27.757z M57.295,60.039c-6.373,0-11.539-5.166-11.539-11.539s5.166-11.539,11.539-11.539S68.833,42.127,68.833,48.5S63.667,60.039,57.295,60.039z");

(可能难以阅读和使用)

B)使用多个字符串和+运算符:

location.setAttributeNS(null,"d","M57.295,27.757"+
"c-11.896,0-21.539,9.64321.539,21.539S57.295,86.5,57.295,86.5s21.539-25.309,21.539-37.205S69.19,27.757,57.295,27.757z "+
"M57.295,60.039"+
"c-6.373,0-11.539-5.166-11.539-11.539s5.166-11.539,11.539-11.539S68.833,42.127,68.833,48.5S63.667,60.039,57.295,60.039z");

(也许是最常见的解决方案)

C)使用\来转义返回字符并获取多行字符串:

location.setAttributeNS(null,"d","M57.295,27.757c-11.896,0\
-21.539,9.64321.539,21.539S57.295,86.5,57.295,86.5s21.539-25.309,\
21.539-37.205S69.19,27.757,57.295,27.757z M57.295,60.039c-6.373,\
0-11.539-5.166-11.539-11.539s5.166-11.539,11.539\
-11.539S68.833,42.127,68.833,48.5S63.667,60.039,57.295,60.039z");

(一个奇怪但有效的解决方案)


有关SVG“d”字符串中可以使用哪些字符的详细信息,请查看http://www.w3.org/TR/SVG/paths.html#PathDataBNF


PS - 确保locationStroke0);不是locationStroke);的拼写错误!