【问题标题】:Polygon not showing up after setAttribute HTMLsetAttribute HTML 后多边形未显示
【发布时间】:2021-06-02 15:31:35
【问题描述】:

我想在我的 html 代码中动态创建一个三角形,稍后我想对其进行修改和使用。 但是从一开始就没有出现。

onclick函数正确触发,新对象出现在html中,但该对象无处可见。

function start_dreiecke() {

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

    var svg = document.createElementNS(xmlns, "svg");
    var polygon = document.createElementNS(xmlns, "polygon");

    polygon.setAttribute('id', 'triangle_' + '01');
    polygon.setAttribute('style', 'width:200px;height:200px;');
    polygon.setAttribute('points', '1000,779 100,779 550,0');
    polygon.setAttribute("style","fill:yellow;stroke:yellow;stroke-width:1;fill-rule:nonzero;");

    svg.appendChild(polygon);
    document.getElementById('canvas').appendChild(svg);
}
#canvas 
{
    position: absolute;
    width: 100px;
    height:100px;
}

svg
{
    position:absolute;
    height:100px;
    width:100px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script>

<h1>Schnittstellendreieck</h1>
<p>Hier ist eine Baustelle für bessere Baustellen.</p>

<!-- Hier werden die Dreiecke generiert. -->

<div id="button">
  <h2 onclick="start_dreiecke()">Start Dreieck</h2>
</div>

<canvas id="canvas"></canvas>
<h3 id="clicked"></h3>

为什么我的三角形没有出现?

【问题讨论】:

  • 如果浏览器不支持 &lt;canvas&gt; 元素或禁用 JavaScript,则 &lt;canvas&gt; 元素的内容仅为 for showing fallback content

标签: javascript html css svg shapes


【解决方案1】:

canvas HTML 元素不应该有子元素。它是一种白板,其中线条和形状没有任何 DOM 表示。另一方面,svg 具有 DOM 表示,因此只需删除 canvas 并将 svg 附加到 DOM 中的其他位置即可。

function start_dreiecke() {

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

    var svg = document.createElementNS(xmlns, "svg");
    var polygon = document.createElementNS(xmlns, "polygon");

    polygon.setAttribute('id', 'triangle_' + '01');
    polygon.setAttribute('style', 'width:200px;height:200px;');
    polygon.setAttribute('points', '1000,779 100,779 550,0');
    polygon.setAttribute("style","fill:yellow;stroke:yellow;stroke-width:1;fill-rule:nonzero;");

    svg.appendChild(polygon);
    document.body.appendChild(svg);
}
#canvas 
{
    position: absolute;
    width: 100px;
    height:100px;
}

svg
{
    position:absolute;
    height:500px;
    width:500px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script>

<h1>Schnittstellendreieck</h1>
<p>Hier ist eine Baustelle für bessere Baustellen.</p>

<!-- Hier werden die Dreiecke generiert. -->

<button onclick="start_dreiecke()" id="button">Start Dreieck</button>

<h3 id="clicked"></h3>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 2012-01-26
    • 2015-01-02
    相关资源
    最近更新 更多