繁体   English   中英

在Vanilla JavaScript中将SVG椭圆转换为图像

[英]Convert SVG Ellipse to Image in Vanilla JavaScript

嗨,我有以下带有Ellipse的SVG:

     <svg xmlns="http://www.w3.org/2000/svg" version="1.1" 
xmlns:xlink="http://www.w3.org/1999/xlink" width="16" height="16">
          <ellipse cx="50%" cy="50%" rx="50%" ry="50%" fill="#fefefe"></ellipse>
        </svg>

我想将上面的一个(字符串格式为btw)转换为一个Image,以便随后可以使用putImageData在画布上使用它。 任何帮助将非常感激。

由于<canvas>元素不允许直接在其上绘制<svg> ,因此必须首先将其“转换”为<img>

这是一个相当简单的过程,涉及(短)步骤:

将SVG放入图像中。 这可以通过创建<img>并将其.src设置为包含SVG的数据URL来完成。

var svg = document.querySelector('svg'),
    img = document.createElement('img');

img.src = 'data:image/svg+xml;utf8,' + svg.outerHTML;

如果SVG包含您需要转义的字符,则可能会稍微复杂一些(尤其是#可能令人讨厌)。

将图像放置在画布上。 画布具有允许将<img> (和其他,但不是<svg> )绘制到其中的context

var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');

//  now that we have the SVG nicely embedded in an image, we can
//  use the image to size the canvas
canvas.width = img.width;
canvas.height = img.height;

//  and draw the image onto the canvas (in the top/left corder) 
//  using the context 
ctx.drawImage(img, 0, 0);

工作的小提琴供您玩耍


由于问题本身被加上svg-filters ,这些需要# ,你可能想的分配改写img.src喜欢的东西:

img.src = svg.outerHTML.replace(/#/g, '%23');

暂无
暂无

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

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