网络地址的svg图片宽高如何获取呢?
直接上代码
d3用的版本是^7.4.4
import * as d3 from "d3";
//获取网络svg图片的宽高
export async function GetSvgInfoFormUrl(url) {
let svg = (await d3.xml(url)).documentElement;
// <svg height="" width=""
const r1 = /(?:[\S\s]+)?<svg(?=.*(height)="(\d+)(?:[^"]+)?")(?=.*(width)="(\d+)(?:[^"]+)?")(?:[\S\s]+)?/;
// <svg viewBox="0 0 1103 711"
const r2 = /(?:[\S\s]+)?viewBox="\d+ \d+ (\d+) (\d+)"(?:[\S\s]+)?/;
// <svg style="height:***px;width:***px"
const r3 = /(?:[\S\s]+)?(?:<svg[^>]+style="(?=.*(height):(\d+)(?:[^>]+)?)(?=.*(width):(\d+)(?:[^>]+)?))(?:[\S\s]+)?/;
let info = { width: 0, height: 0 };
let isSuccess = false;
try {
let data = (new XMLSerializer()).serializeToString(svg)
let str = data
.replace(r1, '{"$1":$2,"$3":$4}').replace(/\$(2|4)/, '0')
.replace(/\$1/, 'height')
.replace(/\$3/, 'width');
if (str.length > 45) isSuccess = false;
else {
isSuccess = true;
info = JSON.parse(str);
}
console.log('r1',str)
if (!isSuccess) {
str = data.replace(r2, '{"width":$1,"height":$2}').replace(/\$(1|2)/, '0');
if (str.length > 45) isSuccess = false;
else {
isSuccess = true;
info = JSON.parse(str);
}
console.log('r2', info);
}
if (!isSuccess) {
str = data
.replace(r3, '{"$1":$2,"$3":$4}')
.replace(/\$(2|4)/, '0')
.replace(/\$1/, 'height')
.replace(/\$3/, 'width');
if (str.length > 45) isSuccess = false;
else {
isSuccess = true;
info = JSON.parse(str);
}
console.log('r3', info);
}
} catch (error) {
console.log(error);
return error;
}
if (isSuccess) return info;
else return '无法正确解析SVG数据';
}
使用的时候直接引入此方法
const svgHW = await GetSvgInfoFormUrl('网络svg图片的地址')
返回:对象 {"height":792,"width":1920}