SVG not showing up when added to HTML

2019-05-29 06:06发布

I am having a very interesting issue, where when I add new SVG elements to a div, only the first time the append is called does a new svg element show up. They work when hard coded, but when they are added onmousedown, they don't show up, even though they are added to the HTML file. I am assuming that it is a problem of my understanding of SVG, and that elements can't be added dynamically, but I have been looking around the internet, and can't find anything on the subject.

You can see that on the $(document).mousedown function, a new circle is appended to the svg holder, however even though it is added to the SVG holder, it will not show up on the web page.

CODE:

HTML:

<div id="svgHolder">
    <!--THIS CIRCLE SHOWS UP-->
    <svg><circle cx='50' cy='50' r='40' stroke='black' stroke-width='1' fill='red' /></svg>
</div>

JQuery/JavaScript:

$(document).ready(function(){

var mouse={
    x:0,
    y:0,
    drawing:false,
    lastX:0,
    lastY:0,

}

$(document).mousedown(function(e){
    console.log('md')
    mouse.x=e.clientX
    mouse.y=e.clientY
    mouse.drawing=true
            //THIS CIRCLE WILL BE ADDED TO THE SVGHOLDER, BUT WILL NOT SHOW UP
    $("#svgHolder").append("<svg><circle cx='"+mouse.x+"' cy='"+mouse.y+"' r='40' stroke='black' stroke-width='1' fill='red' /></svg>");
});

$(document).mouseup(function(e){
    console.log('mu')
    mouse.x=e.clientX
    mouse.y=e.clientY
    mouse.drawing=false
});



$(document).mousemove(function(e){
    console.log('mm')
    mouse.x=e.clientX
    mouse.y=e.clientY
});



});

标签: jquery html svg
2条回答
混吃等死
2楼-- · 2019-05-29 06:16

I think that when you dynamically create a svg node you have to create the namespace.

var ns = "http://www.w3.org/2000/svg";
var svg = document.createElementNS(ns, "svg");
$(svg).append("<circle ...");
查看更多
神经病院院长
3楼-- · 2019-05-29 06:41

Your svg is being inserted but out of your viewport so you can't see it, add some width and height to the svg and also set a proper value for cx and cy properties, i.e.

$(document).mousedown(function(e){
    $("#svgHolder")
    .append("<svg width='100' height='100'><circle cx='50' cy='50' r='40' stroke='black' stroke-width='1' fill='red' /></svg>");
});

Also remember clientX and clientY gives the coordinates relative to the viewport in CSS pixels.

Example1, Example2 and more about SVG.

查看更多
登录 后发表回答