将标签放在“中间"位置SVG路径 [英] Put label in the "center" of an SVG path

查看:437
本文介绍了将标签放在“中间"位置SVG路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在svg文件的多边形上绘制标签.我面临的问题是大致找出该多边形的中心以放置标签,因为路径的坐标为svg格式,需要解析.有没有更简单的方法来确定svg多边形的中心(也许有人可以指出javascript库或代码段)?我正在使用Raphael javascript库来处理svg,但似乎并没有超出标准的svg功能.

I'm trying to draw a label on a polygon of an svg file. The problem I'm facing is to find out roughly the center of this polygon to place the label, as the path's coordinates are in svg format and need to be parsed. Is there an easier way to determine the center of an svg polygon (maybe someone can point out a javascript library or a snippet)? I'm using Raphael javascript library to manipulate the svg, but it doesn't seem to go beyond the standard svg functionality.

推荐答案

基于SVG DOM方法,您可以尝试以下近似方法来执行类似于多边形建议的操作:

You could try the following approximation for doing something similar to the polygon suggestion, based on SVG DOM methods:

var totalPathLength = pathelm.getTotalLength();
var step = totalPathLength / 100;
for(var dist=0; dist < totalPathLength; dist+=step)
{
  var pt = pathelm.getPointAtLength(dist);
  addToAverage(pt.x, pt.y);
}

我认为最简单的方法是使用路径元素的边界框(pathelm.getBBox())的中心,这比多边形建议要简单.

I think the simplest approach is to use the center of the path element's boundingbox (pathelm.getBBox()), that's simpler than the polygon suggestion.

这篇关于将标签放在“中间"位置SVG路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆