使用JavaScript在Django(Python)网页中创建的SVG圆形无法显示
Hey Jason, let's tackle the two problems you're running into with your image-click circle feature:
1. Dynamic Elements Aren't Showing Up
The root issue here is that SVG elements require a specific XML namespace to be recognized correctly. When you use document.createElement('circle'), you're creating a generic HTML element—not an SVG <circle>—which is why hardcoded circles work but dynamically created ones don't.
To fix this, use document.createElementNS() with the official SVG namespace instead:
// Replace this line: var newCircle = document.createElement('circle') // With this: var newCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle')
2. Mouse Coordinates Don't Match SVG's Coordinate System
event.clientX/event.clientY give coordinates relative to the browser viewport, not the SVG's internal user coordinate system. To convert these to the correct position inside the SVG, you need to map the viewport coordinates to the SVG's local space:
svg.onclick = function(event) { // Create a point in the SVG's coordinate system const point = svg.createSVGPoint(); point.x = event.clientX; point.y = event.clientY; // Convert viewport coordinates to SVG coordinates const svgCoords = point.matrixTransform(svg.getScreenCTM().inverse()); // Create the circle with the correct namespace and mapped coordinates var newCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle') newCircle.setAttribute('cx', svgCoords.x) newCircle.setAttribute('cy', svgCoords.y) newCircle.setAttribute('r', '50') newCircle.setAttribute('fill', 'red') svg.append(newCircle) }
Bonus: Ensure SVG Has Explicit Dimensions
If your SVG doesn't have defined width and height attributes, coordinate calculations might still be inconsistent. Update your SVG tag to match your image's actual dimensions:
<svg id="svg" width="800" height="600"> <!-- Replace with your image's width/height --> <image href="data:image/png;base64,{{ my_img }}" width="100%" height="100%"/> <circle cx='50' cy='150' r='50' fill='red'/> </svg>
Full Corrected JavaScript Code
window.addEventListener('DOMContentLoaded', (event) => { const svgElem = document.getElementsByTagName("svg") if (svgElem != undefined && svgElem.length != 0) { const svg = svgElem[0] svg.onclick = function(event) { // Convert viewport coordinates to SVG-local coordinates const point = svg.createSVGPoint(); point.x = event.clientX; point.y = event.clientY; const svgCoords = point.matrixTransform(svg.getScreenCTM().inverse()); // Create valid SVG circle element var newCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle') newCircle.setAttribute('cx', svgCoords.x) newCircle.setAttribute('cy', svgCoords.y) newCircle.setAttribute('r', '50') newCircle.setAttribute('fill', 'red') svg.append(newCircle) } } });
These changes should make your dynamically added circles appear exactly where you click on the image!
内容的提问来源于stack exchange,提问作者JasonFitz

