Después de cambiar con javascript el trazo de una ruta de un svg, el dibujo excede el ancho y la altura de ViewBox. Pero quiero que la ruta, incluido su trazo, sea completamente visible en ViewBox.
var p2 = document.getElementById('p2'); p2.setAttribute("stroke-width", "20"); <svg width="87.827858" height="75.68341" viewBox="0 0 87.827858 75.683411" xmlns="http://www.w3.org/2000/svg" style="background-color: tomato" id="svg1"> <path stroke="green" fill="none" stroke-linejoin="miter" stroke-width="2.84261" stroke-linecap="square" stroke-dashoffset="150" id="p1" d="m 19.767551,1.421305 h 66.639003 c 0,24.787544 0,49.201764 0,72.571424 l -72.237524,0.26727 c -6.271839,-5.9713 -3.416511,-11.33672 -6.595083,-19.10577 -2.708216,-6.6194 6.437081,-17.92492 -3.523279,-17.25944 -10.108666,0.6754 12.178156,-25.397641 15.716883,-36.473484 z" /> </svg> <svg width="87.827858" height="75.68341" viewBox="0 0 87.827858 75.683411" xmlns="http://www.w3.org/2000/svg" style="background-color: tomato" id="svg2"> <path stroke="green" fill="none" stroke-linejoin="miter" stroke-width="2.84261" stroke-linecap="square" stroke-dashoffset="150" id="p2" d="m 19.767551,1.421305 h 66.639003 c 0,24.787544 0,49.201764 0,72.571424 l -72.237524,0.26727 c -6.271839,-5.9713 -3.416511,-11.33672 -6.595083,-19.10577 -2.708216,-6.6194 6.437081,-17.92492 -3.523279,-17.25944 -10.108666,0.6754 12.178156,-25.397641 15.716883,-36.473484 z" /> </svg>¿Cómo saber el tamaño de la ruta, incluido el trazo? Entonces podría cambiar el tamaño del ViewBox.
¿Cómo saber la posición (posición negativa, supongo) de la ruta, incluido el trazo? Entonces podría agregar la transformación de atributos (traducir).
Gracias.
Puede usar getBBox para obtener los límites de una ruta, pero ignora el ancho del trazo. Agregar el ancho del trazo a los límites resultantes puede ayudar hasta cierto punto, como puede ver en el fragmento, pero no puede contar con eso.
El cuadrado rojo representa los límites originales y el azul es un original ampliado (trazo con agregado a cada lado):
const box = d3.select('path').node().getBBox(); console.log(box); d3.select('svg') .append('rect') .attr('x', box.x) .attr('y', box.y) .attr('width', box.width) .attr('height', box.height) .style('stroke', 'red') .style('fill', 'none') d3.select('svg') .append('rect') .attr('x', box.x - 10) .attr('y', box.y - 10) .attr('width', box.width + 20) .attr('height', box.height + 20) .style('stroke', 'blue') .style('fill', 'none') <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <svg width="250" height="200"> <path d="M 100,50 L 190,180 Q 180,60 70,90 Z" stroke="black" fill="none" stroke-width="10" /> <path d="M 100,50 L 190,180 Q 180,60 70,90 Z" stroke="white" fill="none" stroke-width="1" /> </svg>