I need to draw line in SVG in a given width, for example 20px.
What I want to achive is to draw another line, what lines width is the half of the original line, and overlap the original line, but not in the center, but aligned left / bottom.
So, if my x1
and x2
for the original line is 30, then new line x1
and x2
is 25, because to right and left width is 5.
Here is a jsFiddle what I want to achive.
UPDATE On the jsfiddle the lines are ok, because x1 == x2
, but I have problems when the line are not horizontal or vertical.
I am using the following code to figure out the new line x
and y
coordinates, but there is always a little gap.
The tricky part is when I want to rotate that line.
I do not see, where is the error, maybe somewhere with the angle functions?
Or is it good, just SVG / HTML is not precise enough?
<?php
//Init coordinates and thick
$x1 = 30; $y1 = 20;
$x2 = 230; $y2 = 270;
$lineThick = 20;
//get the new data
$newData = getNewPositions($x1, $y1, $x2, $y2, $lineThick);
function getNewPositions($x1, $y1, $x2, $y2, $thick) {
$offset = $thick / 4;
$new['x1'] = $x1;
$new['y1'] = $y1;
$new['x2'] = $x2;
$new['y2'] = $y2;
if ($y1 == $y2) {
$new['y1'] = $y1 - $offset;
$new['y2'] = $y2 - $offset;
return $new;
}
if ($x1 == $x2) {
$new['x1'] = $x1 - $offset;
$new['x2'] = $x2 - $offset;
return $new;
}
$a = abs($y2 - $y1);
$b = abs($x2 - $x1);
$c = sqrt(pow($a,2) + pow($b,2));
$modX = sin($a / $c);
$modY = sin($b / $c);
$new['x1'] = $x1 - ($offset * $modX);
$new['x2'] = $x2 - ($offset * $modX);
$new['y1'] = $y1 + ($offset * $modY);
$new['y2'] = $y2 + ($offset * $modY);
return $new;
}
echo '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . "
";
?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="300" height="300" viewBox="0 0 300 300" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink">
<g>
<line x1="<?php echo $x1; ?>" y1="<?php echo $y1; ?>" x2="<?php echo $x2; ?>" y2="<?php echo $y2; ?>" style="stroke-width:<?php echo $lineThick; ?>; stroke: #000;" />
<line x1="<?php echo $newData['x1']; ?>" y1="<?php echo $newData['y1']; ?>" x2="<?php echo $newData['x2']; ?>" y2="<?php echo $newData['y2']; ?>" style="stroke-width:<?php echo $lineThick / 2; ?>; stroke: #0f0;" />
</g>
</svg>