![](/img/trans.png)
[英]Why can't I see the polygon drawn in this svg and how can I make it visible?
[英]Why can't I make an SVG from an image map?
我有一個img
標記作為<div id="container">
標記的唯一子代。 width
, height
和usemap
都設置在圖像上,就像style="position:absolute;"
和usemap="#amap"
。
我的追求:編寫Javascript,將SVG疊加層添加到顯示圖像映射區域的圖像上,同時保留title
工具提示。 為此,我在head
的script
元素中編寫了以下代碼:
function makeCircle(area)
{
var c = document.createElement("circle");
var coords = area.coords.split(",");
c.setAttribute("cx", coords[0]);
c.setAttribute("cy", coords[1]);
c.setAttribute("r", coords[2]);
c.className = "svg_shape";
var t = document.createElement("title");
t.innerHTML = area.title;
c.appendChild(t);
return c;
}
function makeRect(area)
{
var r = document.createElement("rect");
var coords = area.coords.split(",");
r.setAttribute("x", coords[0]);
r.setAttribute("y", coords[1]);
r.setAttribute("width", coords[2] - coords[0]);
r.setAttribute("height", coords[3] - coords[1]);
r.className = "svg_shape";
var t = document.createElement("title");
t.innerHTML = area.title;
r.appendChild(t);
return r;
}
function makePoly(area)
{
var p = document.createElement("polygon");
var coords = area.coords.split(",");
var coords2 = [];
coords2.push(coords[0]);
for(var i = 1; i < coords.length; i++)
{
if(i % 2 === 0)
coords2.push(" ");
else
coords2.push(",");
coords2.push(coords[i]);
}
p.setAttribute("points", coords2.join(""));
p.className = "svg_shape";
var t = document.createElement("title");
t.innerHTML = area.title;
p.appendChild(t);
return p;
}
function makeSVG()
{
var container = document.getElementById("container");
var image = container.firstElementChild;
var map = document.getElementsByName("amap")[0];
var svg = document.createElement("svg");
container.appendChild(svg);
svg.setAttribute("width", image.width);
svg.setAttribute("height", image.height);
svg.style.position="absolute";
//svg.style.width=image.width;
//svg.style.height=image.height;
var children = map.children;
for(var i = 0; i < children.length; i++)
{
var area = children[i];
var type = area.shape;
if(type==="circle")
{
svg.appendChild(makeCircle(area));
}
else if(type==="rect")
{
svg.appendChild(makeRect(area));
}
else if(type==="poly")
{
svg.appendChild(makePoly(area));
}
}
}
window.onload = makeSVG;
svg_shape
是一個CSS類,基本上只是使形狀可見。
事情是這樣的:即使Chrome的DevTools顯示svg元素是由所有適當的子元素生成的(將其生成的主體HTML復制到新的靜態頁面中也會產生正確的結果),但它不會出現在頁面上。 進一步檢查顯示,SVG的尺寸為0×0,即使它的width
和height
屬性不為零。 是什么賦予了?
您需要使用createElementNS創建SVG元素。
r.className.baseVal = "svg_shape"
為了允許在SVG中使用SMIL,動畫值和基本(非動畫)值是分開的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.