用图像渲染svg到画布 [英] Render svg to canvas with images

查看:293
本文介绍了用图像渲染svg到画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向画布渲染一个svg(以后再保存为png)。

I am rendering an svg to a canvas (to save as png later).

    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" ) );
    };

它适用于base64编码的图像:

It works with base64 encoded images:

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

但是当使用url作为xlink:href值时,它不会将图像渲染到画布:

But when using an url as xlink:href value it does not render the image to the canvas:

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


推荐答案

() 根据设计原样(这里是Gecko的一些细节) ,但似乎其他引擎做出了同样的选择,即使规范只禁止脚本 - https://developer.mozilla.org/en-US/docs/Web/SVG/SVG_as_an_Image

(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)

(原文回答:)你可能遇到了受污染画布的问题。

(the original answer:) It's possible that you have the problem of the tainted canvas.

浏览器有很强的封装数据的政策,所以没有出身(即来自一个域的文档)可以访问来自另一个源的任何类型的数据,除非CORS头明确允许。他们可以向其他域发出请求,但他们永远无法回读结果。这是一个非常强大的规则,它是我们所知道的所有网络安全的基础。

Browsers have very strong policy of encapsulating data so that no origin (i.e. document from one domain) can access any sort of data from another origin, unless explicitly allowed by CORS headers. 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.

一个有趣的结果是,如果画布(或类似画布的实体,如视频)包含来自另一个域(协议/端口)的图片,它被标记为受污染且无法回读。这种污染的状态从画布转移到画布上,所以如果你将一个受污染的画布复制到一个纯画布中,纯粹的画布也会被污染。

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.

如果文档是从与svg图片相同的协议/域/端口提供的,那么您尝试做的事情应该有用。

What you try to do should work if the document is served from the same protocol/domain/port as the svg picture.

这篇关于用图像渲染svg到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆