首页 > 解决方案 > 通过 JavaScript(Django、Python)创建的圆圈未显示在网页中

问题描述

我在我的 Django webapp 中创建了一个页面,该页面显示图像并允许用户单击图像,并且应该在用户单击的图像顶部放置一个圆圈。下面的代码能够获取鼠标点击图像的位置,并在 html 的正确位置添加标签,但实际上不会显示在页面上。如果我将一个圆圈硬编码到 html 中,它会显示得很好。似乎鼠标位于与 SVG 元素不同的坐标系上……我尝试了 event.x、event.pageX 和 event.clientX,但没有发现任何区别。即使我对圆圈的位置进行硬编码,它也不会在点击时显示

html:

{% extends 'main/base.html' %}

{% block head_content %}
{% load static %}
<script type="text/javascript" src="{% static 'js/click.js' %}"></script>
{% endblock %}

{% block content %}

<div class="my-div">

    <div>
        <h1>The Page!</h1>
    </div>
    <form enctype="multipart/form-data" method="POST" action="/mysite/nextpage/">
        {% csrf_token %}

        <svg id="svg">
            <image href="data:image/png;base64,{{ my_img }}"/>
            <!-- Placing a circle manually works just fine! -->
            <circle cx='50' cy='150' r='50' fill='red'/>
            
        </svg>

        <input type="submit" name="submit" class="submit-btn"></input>
    </form>

</div>

{% endblock %}

Javascript:

this.window.addEventListener('DOMContentLoaded', (event) => {
    const svgElem = this.document.getElementsByTagName("svg")

    if (svgElem != undefined && svgElem.length != 0) {
        const svg = svgElem[0]
        const image = svg.firstChild
        svg.onclick = function(event) {
            
            var newCircle = document.createElement('circle')
            newCircle.setAttribute('cx', event.clientX)
            newCircle.setAttribute('cy', event.clientY)
            newCircle.setAttribute('r', '50')
            newCircle.setAttribute('fill', 'red')
            svg.append(newCircle)
        }
    }
});

标签: javascripthtmldjangosvgdom

解决方案


感谢评论中的 @enxaneta 建议 createElementNS,感谢这篇文章(也感谢 @enxaneta)帮助翻译坐标,我得到了代码工作。

this.window.addEventListener('DOMContentLoaded', (event) => {
    const svgElem = this.document.getElementsByTagName("svg")

    if (svgElem != undefined && svgElem.length != 0) {
        const svg = svgElem[0]
        const image = svg.firstChild
        svg.onclick = function(event) {
            
            var newCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle')
            let m = mousePositionSVG(event)
            newCircle.setAttribute('cx', m.x)
            newCircle.setAttribute('cy', m.y)
            newCircle.setAttribute('r', '50')
            newCircle.setAttribute('fill', 'red')
            svg.append(newCircle)
        }
    }
});

function mousePositionSVG(e) {
    let svg = document.querySelector('svg')
    var p = svg.createSVGPoint()
    p.x = e.clientX
    p.y = e.clientY
    var ctm = svg.getScreenCTM().inverse();
    var p =  p.matrixTransform(ctm);
    return p;
}

推荐阅读