gpt4 book ai didi

javascript - 如何使用 JavaScript 在 HTML 中放置 SVG 图像文件

转载 作者:太空狗 更新时间:2023-10-29 14:19:24 24 4
gpt4 key购买 nike

我有一个 SVG 图像文件,我想将它作为 SVG 放入 HTML 页面中。所以我仍然利用高分辨率放大/缩小的优势。

这是我的代码。我将 SVG 放在 SVG 的内部。

代码运行正确,但没有 SVG 出现在浏览器中。

  1. 我怎样才能展示它?
  2. 有没有办法将 SVG 放置为具有所有功能的 SVG(我读了一些问题,但没有一个对我有用)。
// this to draw the svg
var div = document.createElement("div");
div.id="dsvg";
div.class="cdsvg";
div.style.width = "auto";
div.style.height = "210px";

var link='SVGimage.svg';

//creat svg to embed the svg to them
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("height", 210);
svg.setAttribute("width", 500);
//svg.setAttribute('xlink:href', link );

var XLink_NS = 'http://www.w3.org/1999/xlink';

var img = document.createElementNS(svg, 'image');
img.setAttributeNS(null, 'height', '210');
img.setAttributeNS(null, 'width', '500');
img.setAttributeNS(XLink_NS, 'xlink:href', link);

svg.appendChild(img);

var cell3 = row.insertCell(3);
div.appendChild(svg);
cell3.appendChild(div);

这段 HTML 代码可以工作,但是当我将它转换为 JavaScript 时,它就不行了..

<svg id="svgimg" height="60" width="60" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  >

更新:我现在可以将 SVG 视为 img:我添加了库以更改为 SVG(因为我想更改 SVG 中线条和矩形的颜色)

var link='test.svg';
var svgframe = document.createElement('img');
svgframe.id="svgframe";
svgframe.class="svg";
svgframe.setAttribute('src',link );

var SVGs = document.querySelectorAll('.svg');
SVGInjector(SVGs);

但是当我看到 inspect 时,它仍然是 img 标签而不是 SVG??我想要它作为 SVG,所以我可以改变矩形和线条的颜色

最佳答案

看起来您正在尝试动态创建 SVG 元素,然后让它显示在浏览器中。

以下是我过去的粗略做法。此解决方案使用 jQuery 的 html()功能:

    var svgdiv = document.createElement('div');
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('height', heightVar);
svg.setAttribute('width', widthVar);
//Add all your elements to the SVG
svgdiv.appendChild(svg)
//the following shows it in a pop-up window, but the write() and html() functions should be what you need.
window.open().document.write(svgdiv.html());

更准确地说,如果您想将 SVG 放置在文档中的特定位置,例如 div myDiv:

$('#myDiv').html(svgdiv.html());

关于javascript - 如何使用 JavaScript 在 HTML 中放置 SVG 图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25772742/

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