路径"d"属性的 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);

在指定路径数据时要小心。换行会引起麻烦。

作为一个简化的例子:

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);的错别字!

最新更新