From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../svg/namespaces_crash_course/exemplo/index.html | 394 +++++++++++++++++++++ .../web/svg/namespaces_crash_course/index.html | 266 ++++++++++++++ 2 files changed, 660 insertions(+) create mode 100644 files/pt-pt/web/svg/namespaces_crash_course/exemplo/index.html create mode 100644 files/pt-pt/web/svg/namespaces_crash_course/index.html (limited to 'files/pt-pt/web/svg/namespaces_crash_course') diff --git a/files/pt-pt/web/svg/namespaces_crash_course/exemplo/index.html b/files/pt-pt/web/svg/namespaces_crash_course/exemplo/index.html new file mode 100644 index 0000000000..a9fa3f8765 --- /dev/null +++ b/files/pt-pt/web/svg/namespaces_crash_course/exemplo/index.html @@ -0,0 +1,394 @@ +--- +title: Exemplo +slug: Web/SVG/Namespaces_Crash_Course/Exemplo +tags: + - SVG + - XML +translation_of: Web/SVG/Namespaces_Crash_Course/Example +--- +

In this example, we use XHTML, SVG, JavaScript, and the DOM to animate a swarm of "motes". These motes are governed by two simple principles. First, each mote tries to move towards the mouse cursor, and second each mote tries to move away from the average mote position. Combined, we get this very natural-looking behavior.

+ +

This is done completely in W3C Standards–XHTML, SVG, and JavaScript–no Flash or any vendor-specific extensions. This example should work in Firefox 1.5 and above.

+ +

Ver o exemplo

+ +
<?xml version='1.0'?>
+<html xmlns="http://www.w3.org/1999/xhtml"
+	xmlns:svg="http://www.w3.org/2000/svg">
+	<head>
+	<title>A swarm of motes</title>
+	<style type='text/css'>
+	<![CDATA[
+		label, input
+		{
+			width: 150px;
+			display: block;
+			float: left;
+			margin-bottom: 10px;
+		}
+		label
+		{
+			text-align: right;
+			width: 75px;
+			padding-right: 20px;
+		}
+		br
+		{
+			clear: left;
+		}
+	]]>
+	</style>
+	</head>
+	<body onload='update()'>
+		<svg:svg id='display' width='400' height='300'>
+			<svg:circle id='cursor' cx='200'
+cy='150' r='7' fill='#0000ff' fill-opacity='0.5'/>
+		</svg:svg>
+
+		<p>A swarm of motes, governed by two simple principles.
+		First, each mote tries to move towards the cursor, and
+		second each mote tries to move away from the average
+		mote position.	Combined, we get this very natural
+		looking behavior.
+		</p>
+
+		<p>
+		This is done completely in W3C Standards–XHTML,
+		SVG and JavaScript–no flash or any vendor specific
+		extensions.	 Currently, this will work in Mozilla Firefox
+		version 1.5 and above.
+		</p>
+
+		<div>
+		(C) 2006 <a id='emailme' href='#'>Nick Johnson</a>
+
+		<script type='text/javascript'>
+		<![CDATA[
+			// foil spam bots
+			var email = '@riovia.net';
+			email ='nick' + email;
+			document.getElementById('emailme').href = 'mailto:'+email;
+		]]>
+		</script>
+		This software is free for you to use in any way whatsoever,
+		and comes with no warranty at all.
+		</div>
+
+		<form action="" onsubmit="return false;">
+			<p>
+			<label>Number of motes:</label>
+				<input id='num_motes' value='5'/>
+				<br/>
+
+			<label>Max. Velocity:</label>
+				<input id='max_velocity' value='15'/>
+				<br/>
+
+			<label>Attraction to cursor:</label>
+				<input id='attract_cursor' value='6'/>
+				<br/>
+
+			<label>Repulsion from peers:</label>
+				<input id='repel_peer' value='5'/>
+				<br/>
+			</p>
+		</form>
+
+	<script type='text/javascript'>
+	<![CDATA[
+
+		// Array of motes
+		var motes;
+
+		// Get the display element.
+		function Display()
+		{
+			return document.getElementById('display');
+		}
+
+		// Determine dimensions of the display element.
+		// Return this as a 2-tuple (x,y) in an array
+		function Dimensions()
+		{
+			// Our Rendering Element
+			var display = Display();
+			var width = parseInt( display.getAttributeNS(null,'width') );
+			var height = parseInt( display.getAttributeNS(null,'height') );
+
+			return [width,height];
+		}
+
+		// This is called by mouse move events
+		var mouse_x = 200, mouse_y = 150;
+		function OnMouseMove(evt)
+		{
+			mouse_x = evt.clientX;
+			mouse_y = evt.clientY;
+
+			var widget = document.getElementById('cursor');
+			widget.setAttributeNS(null,'cx',mouse_x);
+			widget.setAttributeNS(null,'cy',mouse_y);
+		}
+		document.onmousemove = OnMouseMove;
+
+		// Determine (x,y) of the cursor
+		function Cursor()
+		{
+			return [mouse_x, mouse_y];
+		}
+
+		// Determine average (x,y) of the swarm
+		function AverageMotePosition()
+		{
+			if( !motes )
+				return [0,0];
+
+			if( motes.length == 0 )
+				return [0,0];
+
+			var i;
+			var sum_x=0, sum_y=0;
+			for(i=0; i<motes.length; i++)
+			{
+				sum_x += motes[i].x;
+				sum_y += motes[i].y;
+			}
+
+			return [sum_x/motes.length, sum_y/motes.length];
+		}
+
+		// A nicer, integer random
+		function Rand(modulo)
+		{
+			return Math.round( Math.random() * (modulo-1));
+		}
+
+		// Class Mote
+		function Mote()
+		{
+			// Dimensions of drawing area.
+			var dims = Dimensions();
+			var width = dims[0], height = dims[1];
+
+			// Choose a random coordinate to start at.
+			this.x = Rand( width );
+			this.y = Rand( height );
+
+			// Nil initial velocity.
+			this.vx = this.vy = 0;
+
+			// A visual element---initially none
+			this.elt = null;
+		}
+
+		// Turn this into a class.
+		new Mote();
+
+		// Mote::applyForce() -- Adjust velocity
+		// towards the given position.
+		// Warning: Pseudo-physics -- not really
+		// governed by any /real/ physical principles.
+		Mote.prototype.applyForce = function(pos, mag)
+		{
+			if( pos[0] > this.x )
+				this.vx += mag;
+			else if( pos[0] < this.x )
+				this.vx -= mag;
+
+			if( pos[1] > this.y )
+				this.vy += mag;
+			else if( pos[1] < this.y )
+				this.vy -= mag;
+		}
+
+		// Mote::capVelocity() -- Apply an upper limit
+		// on mote velocity.
+		Mote.prototype.capVelocity = function()
+		{
+			var max = parseInt( document.getElementById('max_velocity').value );
+
+			if( max < this.vx )
+				this.vx = max;
+			else if( -max > this.vx )
+				this.vx = -max;
+
+			if( max < this.vy )
+				this.vy = max;
+			else if( -max > this.vy )
+				this.vy = -max;
+		}
+
+		// Mote::capPosition() -- Apply an upper/lower limit
+		// on mote position.
+		Mote.prototype.capPosition = function()
+		{
+			var dims = Dimensions();
+			if( this.x < 0 )
+				this.x = 0;
+			else if( this.x >= dims[0] )
+				this.x = dims[0]-1;
+
+			if( this.y < 0 )
+				this.y = 0;
+			else if( this.y >= dims[1] )
+				this.y = dims[1]-1;
+		}
+
+		// Mote::move() -- move a mote, update the screen.
+		Mote.prototype.move = function()
+		{
+			// Apply attraction to cursor.
+			var attract = parseInt( document.getElementById('attract_cursor').value );
+			var cursor = Cursor();
+			this.applyForce(cursor, attract);
+
+			// Apply repulsion from average mote position.
+			var repel = parseInt( document.getElementById('repel_peer').value );
+			var average = AverageMotePosition();
+			this.applyForce(average, -repel);
+
+			// Add some randomness to the velocity.
+			this.vx += Rand(3)-1;
+			this.vy += Rand(3)-1;
+
+			// Put an upper limit on velocity.
+			this.capVelocity();
+
+			// Apply velocity.
+			var old_x = this.x, old_y = this.y;
+			this.x += this.vx;
+			this.y += this.vy;
+			this.capPosition();
+
+			// Draw it.
+
+			if( this.elt === null )
+			{
+				var svg = 'http://www.w3.org/2000/svg';
+				this.elt = document.createElementNS(svg,'line');
+				this.elt.setAttributeNS(null,'stroke','green');
+				this.elt.setAttributeNS(null,'stroke-width','3');
+				this.elt.setAttributeNS(null,'stroke-opacity','0.5');
+				Display().appendChild( this.elt );
+			}
+
+			this.elt.setAttributeNS(null,'x1',old_x);
+			this.elt.setAttributeNS(null,'y1',old_y);
+
+			this.elt.setAttributeNS(null,'x2',this.x);
+			this.elt.setAttributeNS(null,'y2',this.y);
+		}
+
+
+		function update()
+		{
+			// First call?
+			if( !motes )
+				motes = [];
+
+			// How many motes should there be?
+			var num = parseInt( document.getElementById('num_motes').value );
+			if( num < 0 )
+				num = 0;
+
+			// Make sure we have exactly that many...
+			// Too few?
+			while( motes.length < num )
+				motes.push( new Mote() );
+			// Or too many?
+			if( num == 0 )
+				motes = [];
+			else if( motes.length > num )
+				motes = motes.slice(0,num-1);
+
+			// Move a random mote
+			if( motes.length > 0 )
+				motes[ Rand( motes.length ) ].move();
+
+			// And do this again in 1/100 sec
+			setTimeout('update()', 10);
+		}
+	]]>
+	</script>
+	</body>
+</html>
+
+ +
+ + + + + +
diff --git a/files/pt-pt/web/svg/namespaces_crash_course/index.html b/files/pt-pt/web/svg/namespaces_crash_course/index.html new file mode 100644 index 0000000000..54a6d077b4 --- /dev/null +++ b/files/pt-pt/web/svg/namespaces_crash_course/index.html @@ -0,0 +1,266 @@ +--- +title: Namespaces Crash Course +slug: Web/SVG/Namespaces_Crash_Course +tags: + - NeedsTranslation + - SVG + - XML +translation_of: Web/SVG/Namespaces_Crash_Course +--- +

As an XML dialect, SVG is namespaced. It is important to understand the concept of namespaces and how they are used if you plan to author SVG content. Versions of SVG viewers prior to the release of Firefox 1.5 unfortunately paid scant attention to namespaces, but they are essential to multi-XML dialect supporting user agents such as Gecko-based browsers which must be very strict. Take some time to understand namespaces now and it will save you all sorts of headaches in the future.

+ +

Background

+ +

It has been a long standing goal of the W3C to make it possible for different types of XML based content to be mixed together in the same XML file. For example, SVG and MathML might be incorporated directly into an XHTML based scientific document. Being able to mix content types like this has many advantages, but it also required a very real problem to be solved.

+ +

Naturally, each XML dialect defines the meaning of the markup tag names described in its specification. The problem with mixing content from different XML dialects in a single XML document is that the tags defined by one dialect may have the same name as tags defined by another. For example, both XHTML and SVG have a <title> tag. How should the user agent distinguish between the two? In fact how does the user agent tell when XML content is something it knows about, and not just a meaningless XML file containing arbitrary tag names unknown to it?

+ +

Contrary to popular opinion, the answer to this question is not "it can tell from the DOCTYPE declaration". DTDs were never designed with mixed content in mind, and past attempts to create mixed content DTDs are now considered to have failed. XML, and some XML dialects (SVG included), don't require a DOCTYPE declaration, and SVG 1.2 won't even have one. The fact that DOCTYPE declarations (usually) match the content in single content type files is merely coincidental. DTDs are for validation only, not identification of content. User agents that cheat and identify XML content using its DOCTYPE declaration cause harm.

+ +

The real answer to the question is that XML content tells the user agent which dialect the tag names belong to by giving the tags explicit "namespace declarations".

+ +

Declaring namespaces

+ +

So what do these namespace declarations look like, and where do they go? Here is a short example.

+ +
<svg xmlns="http://www.w3.org/2000/svg">
+  <!-- more tags here -->
+</svg>
+
+ +

The namespace declaration is provided by the xmlns attribute. This attribute says that the <svg> tag and its child tags belong to whichever XML dialect has the namespace name 'http://www.w3.org/2000/svg' which is, of course, SVG. Note the namespace declaration only needs to be provided once on a root tag. The declaration defines the default namespace, so the user agent knows that all the <svg> tag's descendant tags also belong to the same namespace. User agents check to see if they recognize the namespace name to determine if they know how to handle the markup.

+ +

Note that namespace names are just strings, so the fact that the SVG namespace name also looks like a URI isn't important. URIs are commonly used because they are unique, the intention is not to "link" somewhere. (In fact URIs are used so frequently that the term "namespace URI" is commonly used instead of "namespace name".)

+ +

Redeclaring the default namespace

+ +

So if all the descendants of the root tag are also defined to be in the default namespace, how do you mix in content from another namespace? Easy. You just redefine the default namespace. Here's a short example.

+ +
<html xmlns="http://www.w3.org/1999/xhtml">
+  <body>
+    <!-- some XHTML tags here -->
+    <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px">
+      <!-- some SVG tags here -->
+    </svg>
+    <!-- some XHTML tags here -->
+  </body>
+</html>
+
+ +

In this example the xmlns attribute on the root <html> tag declares the default namespace to be XHTML. As a result it and all its child tags are interpreted by the user agent as belonging to XHTML, except for the <svg> tag. The <svg> tag has its own xmlns attribute, and by redeclaring the default namespace, this tells the user agent that the <svg> tag and its descendants (unless they also redeclare the default namespace) belong to SVG.

+ +

See, namespaces really aren't that hard.

+ +

Declaring namespace prefixes

+ +

XML dialects not only define their own tags, but also their own attributes. By default, attributes don't have a namespace at all, and are only known to be unique because they appear on an element that itself has a unique name. However, sometimes it is necessary to define attributes so that they can be reused on many different elements and still be considered to be the same attribute, independently of the element with which they are used. A very good example of this is the href attribute defined by the XLink specification. This attribute is commonly used by other XML dialects as a means to link to external resources. But how do you tell the user agent which dialect the attribute belongs to, in this case XLink? Consider the following example.

+ +
<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink">
+  <script xlink:href="cool-script.js" type="text/ecmascript"/>
+</svg>
+
+ +

This example has the rather unusual looking attribute xmlns:xlink. As you may guess from the first 'xmlns' part, this is another namespace declaration. However, instead of setting the default namespace, this namespace declaration sets the namespace for something called a "namespace prefix". In this case, we have chosen to use the prefix xlink (the second part) since the prefix will be used to tell the user agent about attributes that belong to XLink.

+ +

As their name suggests, namespace prefixes are used to prefix attribute names and tag names. This is done by putting the namespace prefix and a colon before the attribute name as shown on the <script> tag in the example above. This tells the user agent that that particular attribute belongs to the namespace assigned to the namespace prefix (XLink), and is an attribute that can be used with the same meaning on other tags.

+ +

Note that it is an XML error to use a prefix that hasn't been bound to a namespace name. The binding created by the xmlns:xlink attribute in the example above is absolutely essential if the xlink:href attribute isn't to cause an error. This XLink attribute is also frequently used in SVG on the <a>, <use> and <image> tags among others, so it's a good idea to always include the XLink declaration in your documents.

+ +

As an aside, it's useful to know that namespace prefixes can also be used for tag names. This tells the user agent that that particular tag (but not its children this time!) belongs to the namespace assigned to the prefix. Knowing this will save you some confusion if you come across markup like that in the following example:

+ +
<html xmlns="http://www.w3.org/1999/xhtml"
+      xmlns:svg="http://www.w3.org/2000/svg">
+  <body>
+    <h1>SVG embedded inline in XHTML</h1>
+    <svg:svg width="300px" height="200px">
+      <svg:circle cx="150" cy="100" r="50" fill="#ff0000"/>
+    </svg:svg>
+  </body>
+</html>
+
+ +

Note that because a namespace prefix is used for the <svg:svg> tag and its child <svg:circle>, it wasn't necessary to redeclare the default namespace. In general though it is better to redeclare the default namespace rather than prefix lots of tags in this way.

+ +

Scripting in namespaced XML

+ +

Namespaces affect not only markup, but also scripting. If you write scripts for namespaced XML such as SVG, read on.

+ +

The DOM Level 1 recommendation was created before the original Namespaces in XML recommendation was released; therefore, DOM1 isn't namespace aware. This causes problems for namespaced XML such as SVG. To resolve these problems, DOM Level 2 Core added namespace aware equivalents of all the applicable DOM Level 1 methods. When scripting SVG, it is important to use the namespace aware methods. The table below lists the DOM1 methods that shouldn't be used in SVG, along with their equivalent DOM2 counterparts that should be used instead.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DOM1 (don't use)DOM2 (use these instead!)
createAttributecreateAttributeNS
createElementcreateElementNS
getAttributeNodegetAttributeNodeNS
getAttributegetAttributeNS
getElementsByTagNamegetElementsByTagNameNS (also added to Element)
getNamedItemgetNamedItemNS
hasAttributehasAttributeNS
removeAttributeremoveAttributeNS
removeNamedItemremoveNamedItemNS
setAttributesetAttributeNS
setAttributeNodesetAttributeNodeNS
setNamedItemsetNamedItemNS
+ +

The first argument for all the DOM2 namespace aware methods must be the namespace name (also known as the namespace URI) of the element or attribute in question. For SVG elements this is 'http://www.w3.org/2000/svg'. However, note carefully: the Namespaces in XML 1.1 recommendation states that the namespace name for attributes without a prefix does not have a value. In other words, although the attributes belong to the namespace of the tag, you do not use the tag's namespace name. Instead, you must use null as the namespace name for unqualified (prefixless) attributes. So, to create an SVG rect element using document.createElementNS(), you must write:

+ +
document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+ +

But to retrieve the value of the x attribute on an SVG rect element, you must write:

+ +
rect.getAttributeNS(null, 'x');
+ +

Note that this isn't the case for attributes with a namespace prefix (attributes that don't belong to the same XML dialect as the tag). Attributes such as the xlink:href attribute require the namespace name that was assigned to that prefix (http://www.w3.org/1999/xlink for XLink). Hence to get the value of the xlink:href attribute of an <a> element in SVG you would write:

+ +
elt.getAttributeNS('http://www.w3.org/1999/xlink', 'href');
+ +

For setting attributes that have a namespace, it is recommended (but not required) that you also include their prefix in the second argument so that the DOM can later be more easily converted back to XML (if for instance you want to send it back to the server). For example:

+ +
elt.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'otherdoc.svg');
+ +

As a final example, here's a demonstration of how you should dynamically create an <image> element using script:

+ +
var SVG_NS = 'http://www.w3.org/2000/svg';
+var XLink_NS = 'http://www.w3.org/1999/xlink';
+var image = document.createElementNS(SVG_NS, 'image');
+image.setAttributeNS(null, 'width', '100');
+image.setAttributeNS(null, 'height', '100');
+image.setAttributeNS(XLink_NS, 'xlink:href', 'flower.png');
+
+ +

Conclusão

+ +

Make sure you always declare the namespaces you use in your XML files. If you don't, user agents such as Firefox won't recognize your content and will simply show the XML markup or inform the user that there's an error in the XML. It's a good idea to use a template that includes all the commonly used namespace declarations when creating new SVG files. If you don't already have one, make one up starting with the following code:

+ +
<svg xmlns="http://www.w3.org/2000/svg"
+     xmlns:xlink="http://www.w3.org/1999/xlink">
+</svg>
+
+ +

Even if you don't use all those namespaces in a particular document, there's no harm in including the namespace declarations. It may save you from some annoying errors if you end up adding content from one of the unused namespaces at a later date.

+ +

Um exemplo completo

+ +

Para um exemplo completo, consulte SVG: Namespaces Crash Course: Exemplo.

+ +
+ + + + + +
-- cgit v1.2.3-54-g00ecf