SVG添加到HTML时不显示 [英] SVG not showing up when added to HTML

查看:1034
本文介绍了SVG添加到HTML时不显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个非常有趣的问题,当我向div中添加新的SVG元素时,只有在第一次调用append时才会显示新的svg元素.它们在进行硬编码时可以工作,但是在将它们添加到onmousedown时,即使将它们添加到HTML文件中,也不会显示.我以为这是我对SVG的理解的一个问题,并且无法动态添加元素,但是我一直在Internet上四处寻找,因此找不到关于该主题的任何内容.

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.

您可以在$(document).mousedown函数上看到,一个新的圆圈被添加到svg持有人,但是即使将其添加到SVG持有人,也不会显示在网页上.

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.

代码:

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:

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
});



});

推荐答案

您的svg已插入,但在视口之外,因此看不到,请向width和height >,并为cxcy属性设置适当的值,即

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>");
});

还请记住clientXclientY以CSS像素给出相对于视口的坐标.

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

Example1 有关SVG的更多信息.

这篇关于SVG添加到HTML时不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆