路径转换为绝对命令

路径转换为绝对命令

本文介绍了将 SVG 路径转换为绝对命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 SVG 路径元素,如何将所有路径命令转换为绝对坐标?例如,转换这个路径:

Given an SVG Path element, how can I convert all path commands into absolute coordinates? For example, convert this path:

<path d="M17,42 l100,0 v100 h-100 z"/>

进入这个等效路径:

<path d="M17,42 L117,42 V142 H17 Z"/>

这个问题的动机是这个问题.

推荐答案

这是我想出的 JavaScript 代码:

Here's the JavaScript code I came up with:

function convertToAbsolute(path){
  var x0,y0,x1,y1,x2,y2,segs = path.pathSegList;
  for (var x=0,y=0,i=0,len=segs.numberOfItems;i<len;++i){
    var seg = segs.getItem(i), c=seg.pathSegTypeAsLetter;
    if (/[MLHVCSQTA]/.test(c)){
      if ('x' in seg) x=seg.x;
      if ('y' in seg) y=seg.y;
    }else{
      if ('x1' in seg) x1=x+seg.x1;
      if ('x2' in seg) x2=x+seg.x2;
      if ('y1' in seg) y1=y+seg.y1;
      if ('y2' in seg) y2=y+seg.y2;
      if ('x'  in seg) x+=seg.x;
      if ('y'  in seg) y+=seg.y;
      switch(c){
        case 'm': segs.replaceItem(path.createSVGPathSegMovetoAbs(x,y),i);                   break;
        case 'l': segs.replaceItem(path.createSVGPathSegLinetoAbs(x,y),i);                   break;
        case 'h': segs.replaceItem(path.createSVGPathSegLinetoHorizontalAbs(x),i);           break;
        case 'v': segs.replaceItem(path.createSVGPathSegLinetoVerticalAbs(y),i);             break;
        case 'c': segs.replaceItem(path.createSVGPathSegCurvetoCubicAbs(x,y,x1,y1,x2,y2),i); break;
        case 's': segs.replaceItem(path.createSVGPathSegCurvetoCubicSmoothAbs(x,y,x2,y2),i); break;
        case 'q': segs.replaceItem(path.createSVGPathSegCurvetoQuadraticAbs(x,y,x1,y1),i);   break;
        case 't': segs.replaceItem(path.createSVGPathSegCurvetoQuadraticSmoothAbs(x,y),i);   break;
        case 'a': segs.replaceItem(path.createSVGPathSegArcAbs(x,y,seg.r1,seg.r2,seg.angle,seg.largeArcFlag,seg.sweepFlag),i);   break;
        case 'z': case 'Z': x=x0; y=y0; break;
      }
    }
    // Record the start of a subpath
    if (c=='M' || c=='m') x0=x, y0=y;
  }
}

与问题中的路径一样使用:

Used like so with the path from the question:

var path = document.querySelector('path');
convertToAbsolute(path);
console.log(path.getAttribute('d'));
// M 17 42 L 117 42 V 142 H 17 Z

编辑:这是一个测试页面,其中包含交错的每个命令(绝对和相对)的路径,并显示转换在当前版本的 IE、Chrome、FF 和 Safari 中有效.
http://phrogz.net/svg/convert_path_to_absolute_commands.svg

Edit: Here's a test page with a path that includes every command (absolute and relative) interleaved and shows that the conversion works in the now-current versions of IE, Chrome, FF, and Safari.
http://phrogz.net/svg/convert_path_to_absolute_commands.svg

这篇关于将 SVG 路径转换为绝对命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 08:31