【问题标题】:Drawing an SVG dynamically using javascript使用 javascript 动态绘制 SVG
【发布时间】:2015-10-27 02:26:25
【问题描述】:

我正在尝试绘制一个等腰三角形,它的顶部顶点位于屏幕中间。

我想使用 JavaScript,因为不同用户的屏幕尺寸可能不同,因此必须先找到屏幕的中心。

这是我的代码:

function drawRect(){

        var w = $(document).width();
        var h = $(window).height();
        var halfh = h/2;
        var halfw = w/2;
        var svg = document.createElement("svg");
        var poly = document.createElement("polygon");
        svg.setAttribute("style", "position: fixed;");
        svg.setAttribute("height", ""+h);
        svg.setAttribute("width", ""+w);
        poly.setAttribute("points", ""+halfw+","+halfh+" 0,"+h+" "+w+","+h);
        poly.setAttribute("style", "fill:lime;stroke:purple;stroke-width:1");
        svg.appendChild(poly);

        var svgplace = document.getElementById("carpet");
        svgplace.appendChild(svg);
     }

屏幕上没有出现三角形。但是,如果我在 chrome 上打开“检查元素”控制台,并稍微修改创建的 html 元素,它就会出现! (任何类型的小模组。比如在中间某处添加一个空格)

请帮忙!

提前致谢

【问题讨论】:

标签: javascript jquery html css svg


【解决方案1】:

你需要使用

document.createElementNS("http://www.w3.org/2000/svg", "polygon");

SVG 位于除HTML 之外的自己的命名空间中。因此,您需要使用createElementNS 创建位于SVG 命名空间中的元素。


考虑以下适用于ChromeFirefox 的示例

var newItem = document.createElementNS("http://www.w3.org/2000/svg", "circle");
newItem.setAttribute("cx", ((16 * 1) + 8));
newItem.setAttribute("cy", "50%");
newItem.setAttribute("r", 4);
newItem.setAttribute("fill", "#333333");

document.getElementById("target").appendChild(newItem);
<svg id="target">
</svg>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 2021-10-17
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多