简体   繁体   English

使用图像将svg渲染到画布

[英]Render svg to canvas with images

I am rendering an svg to a canvas (to save as png later). 我正在将svg渲染到画布(稍后保存为png)。

    var svg = document.getElementById("mysvg");
    var svgData = new XMLSerializer().serializeToString( svg );  
    var canvas = <any>document.getElementById("canvas");
    var ctx = canvas.getContext( "2d" );

    var img = document.createElement( "img" );
    img.setAttribute( "src", "data:image/svg+xml;base64," + btoa( svgData ) );

    img.onload = function() {
        ctx.drawImage( img, 0, 0 );
        console.log( canvas.toDataURL( "image/png" ) );
    };

It works with base64 encoded images: 它适用于base64编码的图像:

<image   x="10" y="10"  xlink:href="data:image/jpeg;base64, ...

But when using an url as xlink:href value it does not render the image to the canvas: 但是,当使用url作为xlink:href值时,它不会将图像渲染到画布上:

<image   x="10" y="10"  xlink:href="assets/myimage.png" />

(edit:) Turns out it's by design (here's some details for Gecko, but it seems that other engines made the same choice, even though specs only forbid scripts - https://developer.mozilla.org/en-US/docs/Web/SVG/SVG_as_an_Image ) (edit :)事实证明这是设计使然的(这是G​​ecko的一些细节,但似乎其他引擎也做出了相同的选择,即使规范仅禁止脚本使用-https: //developer.mozilla.org/zh-CN/docs/ Web / SVG / SVG_as_an_Image

(the original answer:) It's possible that you have the problem of the tainted canvas. (原始答案:)您可能遇到了画布污染的问题。

Browsers have very strong policy of encapsulating data so that no origin (ie document from one domain) can access any sort of data from another origin, unless explicitly allowed by CORS headers. 浏览器具有非常强大的封装数据策略,因此除非CORS标头明确允许,否则任何来源(即来自一个域的文档)都无法访问来自另一个来源的任何类型的数据。 They can make requests to other domains, but they can never read back the results. 他们可以向其他域发出请求,但是他们永远不会回读结果。 This is a very strong rule and it underlies all the web security as we know it. 这是一个非常强大的规则,它是众所周知的所有Web安全的基础。

An interesting consequence is that if a canvas (or a canvas-like entity, like video) contains a picture that comes from another domain (protocol / port), it is marked as "tainted" and cannot be read back. 一个有趣的结果是,如果画布(或类似画布的实体,例如视频)包含来自另一个域(协议/端口)的图片,则该图片将被标记为“污迹”,并且无法被读取。 This "tainted" status is carried over from canvas to canvas, so if you copy something from a tainted canvas into a pure one, the pure one gets tainted as well. 这种“污损”状态会在画布之间转移,因此,如果将某物从污损的画布复制到纯画布上,则该纯污渍也会受到污染。

What you try to do should work if the document is served from the same protocol/domain/port as the svg picture. 如果文档是从与svg图片相同的协议/域/端口提供的,则您尝试执行的操作应该会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM