Render SVG with external references to Canvas

北慕城南 提交于 2020-01-02 06:40:20

问题


I'm trying to render an SVG to canvas, using a data: URI and canvas.drawImage(). This works well, except that external images in the SVG are not included on the resulting canvas.

Example HTML (live jsFiddle example):

<canvas id="canvas" width="400" height="400"></canvas>
<div id="container">
    <svg id="mySVG" xmlns="http://www.w3.org/2000/svg" version="1.1">
      <rect width="150" height="150" fill="rgb(0, 255, 0)" stroke-width="1" stroke="rgb(0, 0, 0)"/>
      <image preserveAspectRatio="none" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://upload.wikimedia.org/wikipedia/en/7/70/Example.png" width="80" height="80"></image>
    </svg>
</div>

Javascript:

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    svg = document.getElementById('container').innerHTML,
    img = new Image();

img.onload = function () {
    ctx.drawImage(img, 0, 0);
};
img.src = 'data:image/svg+xml,' + svg;

I've tried setting a timeout before calling drawImage, hoping that it would be a synchronization issue, but it did not seem to help. Any ideas?


回答1:


This is not a canvas issue. It won't work/will look the same even if you are not using the canvas at all and just appending your HTMLImageElement to the DOM. see:

    var svg = document.getElementById('container').innerHTML,
    img = new Image();

img.onload = function () {
    document.body.appendChild(img); // img does not contain Wikipedia image
};
img.src = 'data:image/svg+xml,' + svg;

http://jsfiddle.net/ss5bjooj/2/



来源:https://stackoverflow.com/questions/30399403/render-svg-with-external-references-to-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!