Add border around fixed width SVG?

I am not familiar with the SVG specification, so I was wondering if there would be an easy way to create a border of a certain width around a fixed-width rectangular SVG by simply manipulating the DOM. It seems like it should be feasible, but I don't know where to start.

reference

+4
source share
1 answer

Yes, you can. Let's say you want to have a rectangular frame with four custom blocks and you know that your SVG has viewBox="0 0 400 300" . You can do this from a script:

 var r = document.createElementNS("http://www.w3.org/2000/svg"); r.setAttribute("width", "400"); r.setAttribute("height", "400"); r.setAttribute("fill", "none"); r.setAttribute("stroke", "black"); r.setAttribute("stroke-width", "8"); document.documentElement.appendChild(r); 

The reason you use 8 for the stroke width is because the strokes are drawn in the center along the geometry. Thus, half the stroke of the rectangle (i.e. 4 user units) will lie inside the viewBox and half outside and therefore will not be displayed. You also can:

 var r = document.createElementNS("http://www.w3.org/2000/svg"); r.setAttribute("x", "2"); r.setAttribute("y", "2"); r.setAttribute("width", "398"); r.setAttribute("height", "398"); r.setAttribute("fill", "none"); r.setAttribute("stroke", "black"); r.setAttribute("stroke-width", "4"); document.documentElement.appendChild(r); 

to achieve the same effect.

Note that if your document has content within the 4-unit area where the border will be drawn, say <circle cx="10" cy="10" r="10"/> , then the border will hide it. This is not like the borders of CSS fields that extend beyond the contents of a window. If you want to draw a border on the outside, you need to place the rectangle so that it draws only around the original (0, 0, 400, 300) area and adjust viewBox="" so that it includes the border, For example:

 var r = document.createElementNS("http://www.w3.org/2000/svg"); r.setAttribute("x", "-2"); r.setAttribute("y", "-2"); r.setAttribute("width", "404"); r.setAttribute("height", "404"); r.setAttribute("fill", "none"); r.setAttribute("stroke", "black"); r.setAttribute("stroke-width", "4"); document.documentElement.appendChild(r); document.documentElement.setAttribute("viewBox", "-4 -4 408 408"); 

Now I just remembered from your other question that you are using Batik and manipulating documents with Java, but the above should work if you translate it into the Java DOM (e.g. .getDocumentElement() instead of .documentElement ).

(All of the above has not been verified, but the approach should sound.)

+5
source

Source: https://habr.com/ru/post/1301350/


All Articles