Javascript 中的 SVG 路径 0 - 1 范围转换
SVG Path 0 - 1 Range Conversion in Javascript
我发现这个有用的 PHP 脚本可以使我的 SVG 路径相对于容器,因此在前端实现时响应迅速。
$absolute_path = "M0,67.9586133 M0,67.9586133.....Z";
function regex_callback($matches) {
static $count = -1;
$count++;
$width = 1072.01;
$height = 399.23;
if($count % 2) {
return $matches[0] / $height;
} else {
return $matches[0] / $width;
}
}
$relative_path = preg_replace_callback('(\d+(\.\d+)?)', 'regex_callback', $absolute_path);
来源:Convert SVG path data to 0-1 range
由于目前我正在使用 JavaScript 和 Node,我正在尝试使用 JavaScript 重新创建此函数。这是我到目前为止得到的结果,但我被卡住了,因为返回的数据与输入的数据完全相同。
function replacer(match, svgWidth, svgHeight) {
let count = -1;
count++;
if (count % 2) {
return match[0] / svgHeight;
} else {
return match[0] / svgWidth;
}
}
let svgPath = "M0,67.9586133 M0,67.9586133.....Z"
let nuPath = svgPath.replace('(\d+(\.\d+)?)', replacer);
console.log(nuPath);
任何帮助 -- 方向 and/or 更正表示赞赏。
谢谢!
使用带有全局标志的regular expression:
let nuPath = svgPath.replace(/(\d+(\.\d+)?)/g, replacer);
此外,您必须在函数外定义宽度和高度:
let svgHeight = 399.23;
let svgWidth = 1072.01;
最后你必须清除未使用的函数参数:
let count = -1;
function replacer(match) {
count++;
if (count % 2) {
return match / svgHeight;
} else {
return match / svgWidth;
}
}
我发现这个有用的 PHP 脚本可以使我的 SVG 路径相对于容器,因此在前端实现时响应迅速。
$absolute_path = "M0,67.9586133 M0,67.9586133.....Z";
function regex_callback($matches) {
static $count = -1;
$count++;
$width = 1072.01;
$height = 399.23;
if($count % 2) {
return $matches[0] / $height;
} else {
return $matches[0] / $width;
}
}
$relative_path = preg_replace_callback('(\d+(\.\d+)?)', 'regex_callback', $absolute_path);
来源:Convert SVG path data to 0-1 range
由于目前我正在使用 JavaScript 和 Node,我正在尝试使用 JavaScript 重新创建此函数。这是我到目前为止得到的结果,但我被卡住了,因为返回的数据与输入的数据完全相同。
function replacer(match, svgWidth, svgHeight) {
let count = -1;
count++;
if (count % 2) {
return match[0] / svgHeight;
} else {
return match[0] / svgWidth;
}
}
let svgPath = "M0,67.9586133 M0,67.9586133.....Z"
let nuPath = svgPath.replace('(\d+(\.\d+)?)', replacer);
console.log(nuPath);
任何帮助 -- 方向 and/or 更正表示赞赏。
谢谢!
使用带有全局标志的regular expression:
let nuPath = svgPath.replace(/(\d+(\.\d+)?)/g, replacer);
此外,您必须在函数外定义宽度和高度:
let svgHeight = 399.23;
let svgWidth = 1072.01;
最后你必须清除未使用的函数参数:
let count = -1;
function replacer(match) {
count++;
if (count % 2) {
return match / svgHeight;
} else {
return match / svgWidth;
}
}