How can I get width and height of SVG on Image.load in IE 11

后端 未结 3 1716
迷失自我
迷失自我 2021-01-03 21:43

It works fine everywhere but not in IE 11 (I have not tested other IE versions yet).

var img = new Image();
img.onload = function(){

   alert( \'img: \' + i         


        
相关标签:
3条回答
  • 2021-01-03 22:25

    In html5 standard:

    The IDL attributes width and height must return the rendered width and height of the image, in CSS pixels, if the image is being rendered, and is being rendered to a visual medium; or else the intrinsic width and height of the image, in CSS pixels, if the image is available but not being rendered to a visual medium; or else 0, if the image is not available. LINK

    If img not rendered then IE reserves the right to display 0. And it seems he is doing this.

    With .naturalWidth and .naturalHeight similar situation.

    0 讨论(0)
  • 2021-01-03 22:36

    Well, I don't think you can access the SVG content if it is loaded as a src attribute, and not inline.

    One solution might be to change the way the SVG is loaded, so perhaps load via AJAX, and then append to the document by another means. This gives you a chance to have full access the the SVG source before adding to the document...

    /* use ajax (and in this example jQuery) to get SVG as XML */
    $.get('http://upload.wikimedia.org/wikipedia/en/b/b5/Boeing-Logo.svg', function(svgxml){
    
        /* now with access to the source of the SVG, lookup the values you want... */
        var attrs = svgxml.documentElement.attributes;
        alert( 'img: ' + attrs.width.value + 'x' + attrs.height.value );
    
        /* do something with the svg, like add it to the document for example... */
        $(document.body).append(document.importNode(svgxml.documentElement,true));
    
    }, "xml");
    

    JSFiddle

    This example has used jQuery, and loads the content of the SVG as xml, but you could do it in many ways following the same principle, for example loading as text string, and accessing with regular jQuery methods, or without jQuery at all.

    The moral of the story, is that if you load it via AJAX, you can get a reference to the content of the SVG and have more control over it before it gets added to the page.

    0 讨论(0)
  • 2021-01-03 22:38

    This code works in IE11:

    var img = new Image();
    img.onload = function(){
        document.body.appendChild(this);
        alert( 'img: ' + this.offsetWidth + 'x' + this.offsetHeight);
        document.body.removeChild(this);
    };
    img.src = 'http://upload.wikimedia.org/wikipedia/en/b/b5/Boeing-Logo.svg';
    

    And yes - this solution is not ideal.

    0 讨论(0)
提交回复
热议问题