gpt4 book ai didi

javascript - 如何在 javascript 中将图像添加到 svg 元素?

转载 作者:行者123 更新时间:2023-12-03 07:20:14 25 4
gpt4 key购买 nike

我正在用纯 Javascript 构建一个 svg 元素,但我无法向其中添加图像:

var svgns = "http://www.w3.org/2000/svg";

var svgElement = document.createElementNS(svgns, "svg");
svgElement.setAttributeNS(null, "width", 100);
svgElement.setAttributeNS(null, "height", 100);

var shape = document.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r", 20);
shape.setAttributeNS(null, "fill", "green");

var pngImage = document.createElementNS(svgns, "image");
pgnImage.setAttributeNS(null, "x", 0);
pgnImage.setAttributeNS(null, "y", 0);
pgnImage.setAttributeNS(null, "width", 100);
pgnImage.setAttributeNS(null, "height", 100);
pngImage.setAttributeNS(null, "http://www.freedos.org/images/logos/fdfish-glossy-plain.svg")


svgElement.appendChild(shape);
svgElement.appendChild(pgnImage);

document.body.appendChild(svgElement);

Here is my JSFiddle

最佳答案

你需要这个来设置 href 属性,尽管我不明白为什么在设置 svg 图像时要调用变量 pngImage。

pngImage.setAttributeNS("http://www.w3.org/1999/xlink", "href", "http://www.freedos.org/images/logos/fdfish-glossy-plain.svg")

您还对变量是 pngImage 还是 pgnImage 感到困惑,浏览器调试器会通知您该问题。

Like so

关于javascript - 如何在 javascript 中将图像添加到 svg 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36238218/

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