Pass dynamic SVG widgets to file

Asked

Viewed 272 times

-1

I create SVG elements (circles) with Javascript code dynamically. The problem is that I want to pass these circles to a file with extension .svg. If you create the elements in html, it would just copy them to the file, passed each one’s position variables. But as they are created dynamically, how can I show them in a svg file and then open with an editing program. Example as I create:

<line title="Vertical" x1=60 y1=60 x2=60 y2=460 stroke-width=2 stroke=black />

And in the file to create is:

    fwrite($hndl, "<line title='Vertical' x1='60' y1='60' x2='60' y2='460' stroke-width='2' stroke='black' /> \n");

Now with the code dynamically:

  for (var i = 0; i < steps; i++) {
    var x = stepX * (i + 1);
    var y = stepY * (i + 1);

    //create circle
    var shape = document.createElementNS(
        "http://www.w3.org/2000/svg", "circle");
    shape.setAttributeNS(null, "cx", originX + x);
    shape.setAttributeNS(null, "cy", originY - y);
    shape.setAttributeNS(null, "r", 5);
    shape.setAttributeNS(null, "fill", "green");
    shape.setAttributeNS(null, "class", "draggable");
    shape.setAttributeNS(null, "order", i);
    shape.setAttributeNS(null, "id", i);
    shape.id="circle"+i;
    svg.appendChild(shape);
    }

How can I put them in the file?

1 answer

-1

Well, if I understand correctly you want your user to create a SVG image dynamically with Javascript and then you want to create this image on the server with PHP, right?

If it is, just make a form and send the data you want to it.

Here’s an example (simple, no validation or anything) of what the form might look like:

HTML

<style type="text/css">
body {
    margin: 0;
}

input {
    display: block;
}
</style>

<form action="writesvg.php" method="get">
    <label for="name">Nome do arquivo</label>
    <input type="text" name="name" id="name" placeholder="Digite o nome do arquivo SVG">

    <label for="radius">Tamanho do circulo</label>
    <input type="number" name="radius" id="radius">

    <input type="submit">
</form>

PHP

<?php
if( isset($_GET['name']) && isset($_GET['radius']) ) {

    $r = $_GET['radius'];
    $name = $_GET['name'];
    $size = $r *2;
    $shape = "<circle cx='$r' cy='$r' r='$r'  />";
    $svg = "<?xml version='1.0'?><svg width='$size' height='$size' version='1.1' xmlns='http://www.w3.org/2000/svg'>$shape</svg>";
    $fp = fopen("$name.svg", "w");

    fwrite($fp, $svg);
    fclose($fp);

};
?>
<img src="<?= $name?>.svg">

To get more dynamic, you can work with AJAX, to send the form and then just insert the image via Javascript on the page, without the need for a refresh.

  • Elements are already created dynamically, like this in the code before they are passed to the file. I want to be in SVG code inside the file(svg) and then can edit with software.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.