svgdotjs / svg.js

The lightweight library for manipulating and animating SVG
https://svgjs.dev
Other
10.95k stars 1.07k forks source link

Image SVG size is zero sometimes #1313

Closed FlashTang closed 6 months ago

FlashTang commented 6 months ago

Bug report

Explanation

Here is the test source code : svgjs_img_svg_test.zip To reproduce the issue , open chrome debug console, just refresh the html page several times the width and height are 0 sometimes, but sometimes correct

Fuzzyma commented 6 months ago

Please create a codepen or jsfiddle with the reproduction. You can also post the most relevant code here. I am not downloading any files

FlashTang commented 6 months ago

Please create a codepen or jsfiddle with the reproduction. You can also post the most relevant code here. I am not downloading any files

@Fuzzyma I don't know how to upload svg file to jsfiddle, so here is the relevant code:

<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=3.0, minimum-scale=0.2,shrink-to-fit=YES">
        <title>img_svg_test</title>
    </head>

    <body>

        <div id="canvas"></div>

        <script src="./vendor/svg.min.js"></script>

        <script>

            var draw = SVG().addTo('#canvas')

            var image = draw.image();
            image.on(['load'],function(e){
                console.log("success");
                console.log(image.width());
                console.log(image.height());
            });

            image.on('error',function(e){
                console.log("error");
                console.log(image.width());
                console.log(image.height());
            });

            image.load("./1.svg");

        </script>

    </body>

</html>

and 1.svg

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink"
    preserveAspectRatio="none" x="0px" y="0px" width="200px" height="100px" viewBox="0 0 200 100">
    <defs>
        <g id="Layer0_0_FILL">
            <path fill="#0000FF" stroke="none" d="
M 200 100
L 200 0 0 0 0 100 200 100 Z" />
        </g>
    </defs>

    <g transform="matrix( 1, 0, 0, 1, 0,0) ">
        <use xlink:href="#Layer0_0_FILL" />
    </g>
</svg>
FlashTang commented 6 months ago

Seems i used it wrong , this one is correct :

var image = draw.image('/path/to/image.jpg', function (event) {
  // image loaded
  // this is the loading event for the underlying img element
  // you can access the natural width and height of the image with
  // event.target.naturalWidth, event.target.naturalHeight
})

or

image.load('/path/to/another/image.jpg', callback)

Works fine now 👍

Fuzzyma commented 6 months ago

glad it resolved itself!