SVG - Calculate a transform matrix to an SVG with a different viewbox

670 Views Asked by At

i have an SVG with an viewbox 0 0 500 500 and a transform matrix 0.8,0,0,0.8,54,54

now i want to add this transform to other SVGs. The problem is that all the other SVGs has an different viewbox. So i wrote a function to calculate the transform based on the viewbox ...

getAdjustedTransform('0.8,0,0,0.8,54,54','0 0 500 500','0 0 100 100');

works quite well.

But now i found another problem. Some SVGs has a viewbox with an different height and width (not a sqaure).

I try to fix this issue here

$viewboxWH_diff = $toThisViewBox_arr[2]/$toThisViewBox_arr[3];  
$transform_arr_adjusted[5] = $transform_arr_adjusted[5]*$viewboxWH_diff;

But my calculation is not correct. Any ideas what i make wrong?

function getAdjustedTransform($transform,$viewBox,$toThisViewBox)
{
    $transform_arr      = explode(",", $transform);      // transform from the source SVG
    $viewBox_arr        = explode(" ", $viewBox);        // viewbox from the source SVG
    $toThisViewBox_arr  = explode(" ", $toThisViewBox);             

    $transform_arr_adjusted = array();

    $val_1 = $transform_arr[4] / $viewBox_arr[2];
    $val_2 = $transform_arr[5] / $viewBox_arr[3]; 

    $transform_arr_adjusted[0] = $transform_arr[0];
    $transform_arr_adjusted[1] = $transform_arr[1];
    $transform_arr_adjusted[2] = $transform_arr[2];                
    $transform_arr_adjusted[3] = $transform_arr[3];
    $transform_arr_adjusted[4] = $val_1 * $toThisViewBox_arr[2];
    $transform_arr_adjusted[5] = $val_1 * $toThisViewBox_arr[3];

    //  if viewbox with and height !=
    if($toThisViewBox_arr[2] != $toThisViewBox_arr[3])
    {
        if($toThisViewBox_arr[2] > $toThisViewBox_arr[3])
        {
            $viewboxWH_diff = $toThisViewBox_arr[2]/$toThisViewBox_arr[3];  
            $transform_arr_adjusted[5] = $transform_arr_adjusted[5]*$viewboxWH_diff;
        }
        else
        {
            $viewboxWH_diff = $toThisViewBox_arr[3]/$toThisViewBox_arr[2]; 
            $transform_arr_adjusted[5] = $transform_arr_adjusted[5]*$viewboxWH_diff;
        }
    }

    $transform_arr_adjusted = implode(',',$transform_arr_adjusted);
    return $transform_arr_adjusted;    
}



EDIT:
SVG results from this function
http://jsfiddle.net/nw6ykszn/

1

There are 1 best solutions below

0
On

I meant to put this as a comment, but my reputation doesn't allow me.

I wonder if it is a typo or if the error is in your code as well.

$transform_arr_adjusted[5] = $val_1 * $toThisViewBox_arr[3];

I guess it should be:

$transform_arr_adjusted[5] = $val_2 * $toThisViewBox_arr[3];

Hope it helps!