Scripting <path> data in SVG (reading and modifying)

本文详细介绍了如何在SVG文件中嵌入及运行脚本,如何从脚本中访问和修改&lt;path&gt;元素的数据。通过具体实例展示了使用getAttribute()获取路径数据字符串及利用SVG DOM API解析路径数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://stackoverflow.com/questions/8053487/scripting-path-data-in-svg-reading-and-modifying

Question:

Can anyone really really help me, please? I've been searching for ways to run scripts for my SVG. But all the things i got doesn't match up! And it doesn't contain enough information why he used that set of codes. For example, one used event.target, another had event.getTarget(), and another had event.target.firstchild.data. Can anyone help me, please?

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <path d="M150 0 L75 200 L225 200 Z" />
</svg>

is an example of a path svg right? What i need is to get those coordinates, probably put it in a variable, and use it as coordinates for another svg. So how can i do that? Another thing is how can i change those coordinates by entering numbers in an interface.

So i tried to look for answers, but like i said, i didn't find the info i needed or maybe i just didn't i understand what it showed me.


Answer:

It sounds like you may have four questions:

  1. How do I embed script inside an SVG file?
  2. How do I run script inside an SVG file?
  3. How do I access data for a <path> element from script?
  4. How can I manipulate data for a <path> element from script?

Let's tackle them one at a time:


How do I embed script inside an SVG file?

As described in the SVG specification you can place a <script> element in your document to contain JavaScript code. According to the latest SVG specifications, you do not need to specify a type attribute for your script. It will default to type="application/ecmascript".

  • Other common mime types include "text/javascript""text/ecmascript" (specified in SVG 1.1), "application/javascript", and "application/x-javascript". I do not have detailed information on browser support for all of these, or for omitting the type attribute altogether. I have always had good success with text/javascript.

As with HTML, you may either put the script code directly in the document, or you may reference an external file. When doing the latter, you must use an href attribute (not src) for the URI, with the attribute in the xlink namespace.

<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <script xlink:href="/js/mycode.js" />
  <script><![CDATA[
    // Wrap the script in CDATA since SVG is XML and you want to be able to write
    // for (var i=0; i<10; ++i )
    // instead of having to write
    // for (var i=0; i&lt;10; ++i )
  ]]></script>
</svg>

How do I run script inside an SVG file?

As with HTML, code included in your SVG document will be run as soon as it is encountered. If you place your <script> element above the rest of your document (as you might when putting <script>in the <head> of an HTML document) then none of your document elements will be available when your code is running.

The simplest way to avoid this is to place your <script> elements at the bottom of your document:

<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <!-- all SVG content here, above the script -->
  <script><![CDATA[
    // Now I can access the full DOM of my document
  ]]></script>
</svg>

Alternatively, you can create a callback function at the top of your document that is only invoked when the rest of the document is ready:

<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
  <title>SVG Coordinates for Embedded XHTML Elements</title>
  <script>document.documentElement.addEventListener('load',function(){
    // This code runs once the 'onload' event fires on the root SVG element
    console.log( document.getElementById('foo') );
  },false)</script>
  <path id="foo" d="M0 0" />
</svg>

How do I access data for a <path> element from script?

There are two ways to access most information about elements in SVG: you can either access the attribute as a string through the standard DOM Level 1 Core method getAttribute(), or you can use the SVG DOM objects and methods. Let's look at both:

Accessing path data through getAttribute()

Using getAttribute() returns the same string as you would see when you view source:

<path id="foo" d="M150 0 L75 200 L225 200 Z" />
<script><![CDATA[
  var path = document.getElementById('foo');
  var data = path.getAttribute('d');
  console.log(data);
  //-> "M150 0 L75 200 L225 200 Z"
]]></script>
  • Pros: very simple to call; you don't have to know anything about the SVG DOM
  • Con: since you get back a string you have to parse the attribute yourself; for SVG <path> data, this can be excruciating.

Accessing path data through SVG DOM methods

<path id="foo" d="M150 0 L75 200 L225 200 Z" />
<script><![CDATA[
  var path = document.getElementById('foo');

  // http://www.w3.org/TR/SVG/paths.html#__svg__SVGAnimatedPathData__normalizedPathSegList
  // See also path.pathSegList and path.animatedPathSegList and path.animatedNormalizedPathSegList
  var segments = path.normalizedPathSegList ;

  for (var i=0,len=segments.numberOfItems;i<len;++i){
    var pathSeg = segments.getItem(i);
    // http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSeg
    switch(pathSeg.pathSegType){
      case SVGPathSeg.PATHSEG_MOVETO_ABS:
        // http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSegMovetoAbs
        console.log("Move to",pathSeg.x,pathSeg.y);
      break;
      case SVGPathSeg.PATHSEG_LINETO_ABS:
        // http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSegLinetoAbs
        console.log("Line to",pathSeg.x,pathSeg.y);
      break;
      case SVGPathSeg.PATHSEG_CLOSEPATH:
        // http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSegClosePath
        console.log("Close Path");
      break;
    }
  }
]]></script>

The above script produces the following output:

Move to 150 0
Line to 75 200
Line to 225 200
Close Path
  • Pros: path data is parsed for you; you get exact numbers from the API itself; using normalizedPathSegList takes relative commands and makes them absolute for you; if SMIL animation is changing the path data, using the non-animated pathSegList can give you access to the base, non-animated information not available via getAttribute().

  • Cons: Sweet chimpunks a-flame, look at that code! And that doesn't even handle all the possible path segments available.

Because it can be hard to read the W3C specs for SVG DOM, many years ago I created an online tool for browsing what properties and objects exist. You may use it here:http://objjob.phrogz.net/svg/hierarchy


How can I manipulate data for a <path> element from script

Similar to the above, you can either create a new string and use setAttribute() to shove it onto the object, or you can manipulate the SVG DOM.

Manipulating path data using setAttribute()

<path id="foo" d="M150 0 L75 200 L225 200 Z" />
<script><![CDATA[
  var path = document.getElementById('foo');
  path.setAttribute('d','M150,0 L150,100 200,300 Z');
]]></script>

Manipulating path data using SVG DOM

<path id="foo" d="M150,0 L75,200 l150,0 Z" />
<script><![CDATA[
  var path = document.getElementById('foo');
  var segments = path.pathSegList;
  segments.getItem(2).y = -10;
]]></script>

In general, you just have to modify the properties of the various SVGPathSeg subclass instances; the changes are made immediately in the DOM. (With the above example, the original triangle is skewed as the last point is moved up slightly.)

When you need to create new path segments, you need to use methods like var newSegment = myPath.createSVGPathSegArcAbs(100,200,10,10,Math.PI/2,true,false) and then use one of the methods to stick this segment into the list, e.g. segments.appendItem(newSegment).


### PHP and HTML Code Explanation with Error Handling and Form Validation Form validation is a critical aspect of web development to ensure that the data entered by users meets specific criteria. A common way of showing validation errors is in a box on the top of the screen, and this behavior is relatively easy to build with the HTML5 form validation APIs[^1]. However, for more robust error handling, server-side validation using PHP is essential. Below is an example of a simple HTML form combined with PHP for both client-side and server-side validation: #### Example: Simple Contact Form with Validation ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Contact Form</title> <style> .error { color: red; } </style> </head> <body> <?php // Initialize variables for error messages $nameErr = $emailErr = ""; $name = $email = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { // Validate Name if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); // Check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/", $name)) { $nameErr = "Only letters and white space allowed"; } } // Validate Email if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); // Check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>Contact Form</h2> <p><span class="error">* required field</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name" value="<?php echo $name;?>"> <span class="error">* <?php echo $nameErr;?></span> <br><br> E-mail: <input type="text" name="email" value="<?php echo $email;?>"> <span class="error">* <?php echo $emailErr;?></span> <br><br> <input type="submit" name="submit" value="Submit"> </form> </body> </html> ``` In the above code: - The `test_input` function ensures that user input is sanitized to prevent potential security issues such as SQL injection or cross-site scripting (XSS)[^2]. - Client-side validation can be enhanced using HTML5 attributes like `required`, but it should never replace server-side validation. - Errors are displayed dynamically near their respective fields using PHP logic. Programmer errors, such as forgetting to validate user input or mistyping variable names, are bugs that must be addressed during development[^2]. These types of errors cannot be handled at runtime because they indicate mistakes in the code itself. Additionally, decision trees used for data analysis may require careful consideration when pruning. Pre-pruning risks underfitting by prematurely stopping splits, while post-pruning helps mitigate this issue[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值