[英]Circles not showing up in webpage when created via JavaScript (Django, Python)
我在我的 Django webapp 中創建了一個頁面,該頁面顯示圖像並允許用戶單擊圖像,並且應該在用戶單擊的圖像頂部放置一個圓圈。 下面的代碼可以獲取鼠標在圖片上點擊的位置,並在 html 的正確位置添加標簽,但實際上並不會顯示在頁面上。 如果我在 html 中硬編碼一個圓圈,它會顯示得很好。 似乎鼠標位於與 SVG 元素不同的坐標系上……我嘗試了 event.x、event.pageX 和 event.clientX,但沒有發現任何區別。 即使我對圓圈的 position 進行硬編碼,它也不會在點擊時顯示
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)
}
}
});
感謝評論中的 @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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.