Necesito crear trazos similares en longitud pero con diferentes ángulos de rotación, así que en lugar de tener varias líneas de códigos redundantes, preferí usar JavaScript como sigue;
function stroke(rot) { var dash=document.createElementNS("http://www.w3.org/2000/svg", "path"); dash.setAttributeNS(null,"id","dash"); dash.setAttributeNS(null,"d","M 180 0 L 200 0"); dash.setAttributeNS(null,"transform","rotate(+"+rot+" 200 200)"); dash.setAttributeNS(null,"fill","none"); dash.setAttributeNS(null, "stroke","black"); dash.setAttributeNS(null, "stroke-width","5"); document.appendChild(dash); } for(i=0;i<360;i+=10) stroke(i);i es el valor al que se rotará el trazo cuando se llame al trazo(i).
Revisé una solución desde aquí para arreglar mi código, pero desafortunadamente esto no funciona, ¿alguna solución para esto?
El problema es que intenta agregar rutas en un documento, no en un elemento SVG.
const svgTarget = document.getElementById("draw"); function stroke(rot) { let dash = document.createElementNS("http://www.w3.org/2000/svg", "path"); dash.setAttributeNS(null, "id", "dash"); dash.setAttributeNS(null, "d", "M 180 5 L 200 5"); dash.setAttributeNS(null, "transform", "rotate(+" + rot + " 200 200)"); dash.setAttributeNS(null, "fill", "none"); dash.setAttributeNS(null, "stroke", "black"); dash.setAttributeNS(null, "stroke-width", "5"); svgTarget.appendChild(dash); } for (i = 0; i < 360; i += 10) stroke(i); <svg id="draw" viewBox="0 0 400 400" width="200px" height="200px"></svg>Dado que un <svg id="draw"> analizado ya está en el NameSpace correcto;
puede agregar contenido con cadenas, no es necesario agregar esos <path> en el espacio de nombres SVG (nuevamente)
Como dijo Robert, un <circle> con stroke-dasharray da un mejor resultado (los caminos dibujados son rectos),
no requiere JavaScript y se puede cambiar fácilmente.
for (i = 0; i < 360; i += 10) { document.getElementById("draw") .innerHTML += `<path d="M180 5L200 5" transform="rotate(${i} 200 200)" fill="none" stroke="black" stroke-width="5"/>`; } <svg id="draw" viewBox="0 0 400 400" height="180px"></svg> <svg id="circle" viewBox="0 0 400 400" height="180px"> <circle stroke-width="5" r="197.5" fill="none" stroke="red" cx="200" cy="200" pathLength="72" stroke-dasharray="1"/> </svg>