gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:50:10 24 4
gpt4 key购买 nike

嘿,大家好,我有以下带有椭圆的 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>

我想将上面的图像(顺便说一句,它是字符串格式)转换为图像,以便我可以使用 putImageData 在 Canvas 上使用它。任何帮助将不胜感激。

最佳答案

作为 <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 包含需要转义的字符(尤其是 # 可能会很糟糕),这可能会更复杂一些。

将图像放置到 Canvas 上。 Canvas 有 context 这允许 <img> (和其他,但不是 <svg> )被吸引进去。

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

a working fiddle for you to play with

<小时/>

由于问题本身被标记为 svg-filters这些需要 # ,您可能需要重写 img.src 的赋值类似:

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

关于javascript - 在 Vanilla JavaScript 中将 SVG 椭圆转换为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41059284/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com