繁体   English   中英

如何确保上传的 SVG 有 width 和 height 属性

[英]How to ensure uploaded SVG has width and height Attributes

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

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

如果我有 SVG 作为文件(通过输入类型 =“文件”),如果它丢失,我该如何添加宽度和高度?

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

 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]);

我不得不 go 通过 SVG 找到 SVG 元素的实例,因为我测试的一些 SVG 有额外的标签或评论弄乱了它。 此外,宽度和高度的 300 值刚刚组成,但似乎没问题,可能可以使用视图框尺寸代替,但它适用于我

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM