I'm having some trouble getting svgs loaded from an API to work, some svgs seem to have a viewbox property some don't. Some svgs load correctly and fill the container, others are tiny, and others don't display at all (possibly too large).
The JSON data can be found here:
CodePudding user response:
I managed to solve my issue by modifying all the svgs using the following script I cobbled together.
const fs = require("fs");
const path = require("path");
// Get list of icons from the icons directory
const icons = fs.readdirSync(path.join(__dirname, "icons"));
const modifySvg = (filepath) => {
// Load the SVG file
let svg = fs.readFileSync(filepath, "utf8");
// Check if svg has viewbox
const hasViewBox = svg.includes("viewBox");
if (!hasViewBox) {
console.log("No viewBox found");
// Check if width and height are set
const hasWidth = svg.includes("width");
const hasHeight = svg.includes("height");
if (!hasWidth || !hasHeight) {
console.log("No width or height found");
} else {
console.log("Width and height found");
console.log("Adding viewBox");
// Get width property
const widthStr = svg.match(/width="([^"]*)"/)[0];
const width = widthStr.replace(/"/g, "").replace("width=", "");
// Get height property
const heightStr = svg.match(/height="([^"]*)"/)[0];
const height = heightStr.replace(/"/g, "").replace("height=", "");
console.log({ width, height });
// Add viewBox to end of svg tag
const viewBox = `viewBox="0 0 ${width} ${height}"`;
svg = svg.replace(/<svg/, `<svg ${viewBox}`);
// Make width and height are 100%
svg = svg.replace(/width="[^"]*"/, `width="100%"`);
svg = svg.replace(/height="[^"]*"/, `height="100%"`);
// Write the file
fs.writeFileSync(filepath, svg);
console.log(`Saved ${filepath}`);
}
}
};
//Loop icons
icons.forEach((icon) => {
// Get file path
const filePath = path.join(__dirname, "icons", icon);
// Modify svg
modifySvg(filePath);
});
Hope this helps someone!