框架中的实用程序,用于更轻松地定义 SVG 路径字符串

Utility in framework for defining SVG path strings more easily?

本文关键字:定义 SVG 字符串 路径 实用程序 用于 框架      更新时间:2023-09-26

我正在通过Raphael框架尝试svg功能(它的路径文档在这里)。 我发现编写路径字符串非常乏味,因为在创建新路径或查看已写入的路径时,我必须不断查找格式规范。 是否有简化此过程的框架? 例如,不必编写以下内容:

function pathStringForBoxWithQuad(x1, y1, x2, y2) {
    var edgeLength = 8;
    var str = "M " + (x2 + edgeLength) + " " + y1; // move to top right
    str += " L " + x1 + " " + y1; // line to top left
    str += " L " + x1 + " " + y2; // line to bottom left
    str += " L " + (x2 + edgeLength) + " " + y2; // line to bottom right
    str += " Q " + x2 + " " + (y1 + (y2 - y1) / 2) + " " + (x2 + edgeLength) + " " + y1; // quadratic back to top right
    str += " Z";
    return str;
}

你可以写如下的东西,但它会返回相同的字符串:

function pathStringForBoxWithQuad(x1, y1, x2, y2) {
    var edgeLength = 8;
    var str = new SVGPathString()
            .moveTo(x2 + edgeLength, y1)
            .lineTo(x1, y1)
            .lineTo(x1, y2)
            .lineTo(x2 + edgeLength, y2)
            .quadTo(x2, (y1 + (y2 - y1) / 2), x2 + edgeLength, y1 );
    return str;
}

流行的框架中是否存在类似于第二种方法的东西? 我发现这种类型的路径构建对读者更加友好。

我也在寻找类似的东西,但现在我最终使用 Underscore.js 为 SVG 命令创建模板。 类似的东西。

var commands = {
    line: _.template('M<%= x1 %>,<%= y1 %> L<%= x2 %>,<%= y2 %>'),
  .....
}
....
commands.line({
    x1: 0,
    y1: 0,
    x2: 0,
    y2: 10        
})

你想要的东西看起来有点类似于SVG Tiny 1.2中的SVGPath API,没有字符串化。这些路径对象不是为了在序列化上浪费时间,而是直接分配。在当前所有浏览器中,SVGPath API 仅由 Opera AFAIK 实现。

不过,SVG WG 正在考虑改进 SVG2 的路径 API,所以希望将来会有更好的东西。

总是有 SVG DOM。

  var path = document.getElementById("<pathId>");
  var segments = path.pathSegList;

当您需要创建新的路径段时,需要使用诸如

var newSegment = path.createSVGPathSegArcAbs(...) 

调用segments.appendItem or segments.insertItemBefore 以添加它。有关更多详细信息,请参阅 http://www.w3.org/TR/2003/REC-SVG11-20030114/paths.html#DOMInterfaces。

相关文章: