FabricJS loadSVGFromURL() 在本地主机上不工作

FabricJS loadSVGFromURL() not working at localhost

我知道这个问题与文件来源有些关系。当我从安全 URL 中设置 fiddle 时,它不起作用 (https://jsfiddle.net/fccarminati/c7f53g9j/). However, if I access it from non-secure URL it does (http://jsfiddle.net/fccarminati/c7f53g9j/)。

现在,当我尝试在本地进行这项工作时,我搭建了一个 Apache 服务器来托管我的文件。它没有在控制台给我一个跨源错误,但它也没有正确导入 svg。

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <button id="btnAddSVG" type="button" class="btn btn-default">Add SVG</button>
    <canvas width="800" height="600" id="c"></canvas>
    <script src="bower_components/jquery/dist/jquery.min.js"></script>
    <script src="js/fabric.js"></script>
    <script src="js/test.js"></script>
</body>
</html>

JS

 var canvas = new fabric.Canvas('c');

 //add sticker
$('#btnAddSVG').on('click', function(){

    fabric.loadSVGFromURL('http://localhost:81/appcoperia/stickers/1.svg', function(objects) { 
        var group = new fabric.PathGroup(objects, { 
            left: 100, 
            top: 100, 
            width: 150, 
            height: 150 
        });

        canvas.add(group); 
        canvas.renderAll(); 

    }); 

});

有谁知道我还应该研究哪些其他问题?

我没有足够的声誉来发表评论,所以...

When I put up a fiddle from a secure URL, it doesn't work (https://jsfiddle.net/fccarminati/c7f53g9j/)

您的 SVG 文件 url 必须使用 HTTPS。因此,尝试在您的 js 源文件中更改为 https://fabricjs.com/assets/1.svg。它可能不是第一次工作。此外,您必须尝试 open the url on new tab of your browser 并接受安全警告。

"Now when trying to make this work locally, ..."

我会尝试在本地 运行 并更新此答案。 (但是,以防万一,这不是 "PORT 81" 问题,对吧?您的 Apache 运行 正在 :81?)


[更新] 您的代码 LGTM。我这样做了(并且有效):

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <button id="btnAddSVG" type="button" class="btn btn-default">Add SVG</button>
    <canvas width="800" height="600" id="c"></canvas>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.3/fabric.min.js" integrity="sha256-BeLYOR7hF1X4xXnJJkOvwf2nNkZK9Fe2OJgoa2/maqA=" crossorigin="anonymous"></script>
    <script>
        var canvas = new fabric.Canvas('c');
        //add sticker
        $('#btnAddSVG').on('click', function(){

            fabric.loadSVGFromURL('http://0.0.0.0:8000/1.svg', function(objects) { 
                var group = new fabric.PathGroup(objects, { 
                    left: 100, 
                    top: 100, 
                    width: 150, 
                    height: 150 
                });

                canvas.add(group); 
                canvas.renderAll(); 

            }); 

        });
    </script>
</body>
</html>

注意URL/文件路径。就我而言,我的服务器 运行 位于 localhost:8000,SVG 与 html 文件位于同一文件夹中。