【问题标题】:How to ensure uploaded SVG has width and height Attributes如何确保上传的 SVG 具有 width 和 height 属性
【发布时间】:2022-01-20 15:57:25
【问题描述】:

我的用户可以上传图像文件,可以是 SVG。

我需要确保所有 SVG 都具有宽度和高度属性,以应对稍后发生的事情。

如果我将 SVG 作为一个文件(通过输入 type="file"),如果它丢失了,我该如何为其添加宽度和高度?

【问题讨论】:

标签: javascript jquery node.js svg


【解决方案1】:

我最终做了以下事情,尽管我确信它可以以更好的方式改进/完成

 let svgReader = new FileReader();
               
        svgReader.onload = function (e) {
            let svg = $(e.target.result);

            for(let i =0;i<svg.length;i++) {
                if (svg[i] instanceof SVGElement) {
                    svg = $(svg[i]);
                    break;
                }
            }

            let width = svg.attr("width");
            let height = svg.attr("height");
            if (height == null || height == undefined) {
                svg.attr("height", 300);
            }

            if (width == null || width == undefined) {
                svg.attr("height", 300);
            }

            let svgFile = new XMLSerializer().serializeToString(svg[0]);
            let new file = new File([svgFile], files[index].name, {type: "image/svg+xml"});
        };
svgReader.readAsText(files[0]);

我必须通过 SVG 找到 SVG 元素的实例,因为我测试的一些 SVG 有额外的标签或 cmets,否则会搞砸。另外,宽度和高度的 300 值是刚刚组成的,但似乎还可以,可能可以使用视图框尺寸代替,但它适用于我

【讨论】:

    猜你喜欢
    • 2011-04-03
    • 2012-10-28
    • 1970-01-01
    • 2021-09-25
    • 2014-11-13
    • 2011-04-23
    • 2013-05-14
    • 2011-01-10
    • 1970-01-01
    相关资源
    最近更新 更多