PHP code example of kaareln / php-svg-path-data

1. Go to this page and download the library: Download kaareln/php-svg-path-data library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kaareln / php-svg-path-data example snippets


$path = new SVGPath();

$data = new SVGPathData();

$data->addCommand(new Move(0, 0));

$topLine = new Line(20, 0);
$data->addCommand($topLine);

$rightLine = new Line(20, 20);
$data->addCommand($rightLine);

// at this point I have a references to $topLine and $rightLine, which I can use to modify individually, for example I can move them by 20px

$topLine->x += 20;
$rightLine->x += 20;

// convert the instructions to string and save as d param
$path->setArgument('d', $data->__toString());

// assume $path is an instanceof SVGPath

$pathData = SVGPathData::fromString($path->getArgument('d'));

// loop for each command in reverse order and possibly change/read parts of the path
foreach ($pathData as $command) {
  if ($command instanceof Line) {
    // move each line coordinates by 20px
    $command->x += 20;
  }
}

// alternatively you can use `transform` method that runs against each command and allows replacing them. In this example I replace all bezier curves with straight lines
$pathData->transform(function (PathDataCommandInterface $command) {
  if ($command instanceof BezierCurve) {
    return new Line($command->x, $command->y);
  }
});

// update the path
$path->setArgument('d', $pathData->__toString());