Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate in SVG coordinates?

Given a simple SVG containing a line of some width from top left to bottom right.

<svg><line x1="0px" y1="0px" x2="100%" y2="100%"
style="stroke: #aaa; stroke-width: 6px"/></svg>

The line gets positioned amd stretched with CSS. Since it always spans the whole SVG, I can just set width and height of the SVG to do so. The problem is that edges of the line get cut in the corners.

SVG line with cut off edges

Since I want to see the whole line including its corners. I thought about adding which is twice the stroke width to the SVG size. Then the line could start at 6px from left and top and go to 100% - 6px. How can I express this calculated coordinates in SVG? I would need something like the calc() in CSS3.

like image 344
danijar Avatar asked Oct 20 '22 07:10

danijar


1 Answers

You can try adding id="lineId" to your html element, and then in js:

<html>
<body onload="resizeLine();">

<svg width="500px" height="150px"><line id="lineId" x1="6px" y1="6px" x2="100%" y2="100%"
style="stroke: #aaa; stroke-width: 6px"/></svg>

<script>
function resizeLine() {
    alert('Note that line is not resized yet.');
    var line = document.getElementById('lineId'),
        lineWidth = line.getBoundingClientRect().width,
        lineHeight = line.getBoundingClientRect().height;
    line.setAttribute('x2', lineWidth-6);
    line.setAttribute('y2', lineHeight-6);
}
</script>
</body>
</html>
like image 111
Rebelek Avatar answered Oct 23 '22 00:10

Rebelek