如何在客户端使用image.onload返回值

时间:2017-10-09 05:34:13

标签: javascript svg export client-side

我尝试使用Blob从svg元素导出png图像。在这里,当我点击锚标签时,图像已被导出但由于在完成点击事件后调用的异步方法(image.onload())没有内容。如何解决这个问题?

<body>
    <a id="export">Click To Export</a>
    <div id="container" width=500px height=200px>
        <svg id="myViewer" width="500px" height="200px" xmlns="http://www.w3.org/2000/svg">
            <rect x="50" y="20" width="150" height="150" style="fill:blue;stroke:pink;stroke-width:5;fill-opacity:0.1;stroke-opacity:0.9"
            />
        </svg>
    </div>
    <script>
        document.getElementById('export').onclick = function () {
            var tag = document.getElementById('export');
            tag.download = 'Sample' + "." + 'png';
            tag.href = getCanvaElement().toDataURL();
        }

        function getCanvaElement() {
            var svgText = document.getElementById("myViewer").outerHTML;
            var svg = new Blob([svgText], { type: "image/svg+xml;charset=utf-8" });
            var domURL = self.URL || self.webkitURL || self;
            var url = domURL.createObjectURL(svg);
            var element = document.createElement('canvas');
            var ctx = element.getContext("2d");
            var image = new Image;
            image.onload = function () {
                ctx.drawImage(this, 0, 0);
                domURL.revokeObjectURL(url);
            };
            image.src = url;
            return element;
        }
    </script>
</body>

示例链接:http://jsfiddle.net/kyjs655r/347/

1 个答案:

答案 0 :(得分:0)

您可以在Promise加载事件

中使用async/await构造函数和resolve()<canvas> <img>元素
 document.getElementById('export').onclick = async function() {
   var tag = document.getElementById('export');
   tag.download = 'Sample' + "." + 'png';
   const canvas = await getCanvaElement();
   tag.href = canvas.toDataURL();
 }

 function getCanvaElement() {
   return new Promise(resolve => {
     var svgText = document.getElementById("myViewer").outerHTML;
     var svg = new Blob([svgText], {
       type: "image/svg+xml;charset=utf-8"
     });
     var domURL = self.URL || self.webkitURL || self;
     var url = domURL.createObjectURL(svg);
     var element = document.createElement('canvas');
     var ctx = element.getContext("2d");
     var image = new Image;
     image.onload = function() {
       ctx.drawImage(this, 0, 0);
       domURL.revokeObjectURL(url);
       resolve(element)
     };
     image.src = url;
   })
 }

jsfiddle http://jsfiddle.net/kyjs655r/351/