Compare Revisions

SVG In HTML Introduction

Change Revisions

Revision 54266:

Revision 54266 by Nickjohnson on

Revision 54267:

Revision 54267 by Nickolay on

Title:
SVG In HTML Introduction
SVG In HTML Introduction
Slug:
SVG_In_HTML_Introduction
SVG_In_HTML_Introduction
Tags:
SVG
SVG
Content:

Revision 54266
Revision 54267
n97    <h3 name="Another_Example">n
98      Another Example
99    </h3>
100    <p>
101      In this example, we use XHTML, SVG and the Javascript DOM 2
> to animate a swarm of "motes". These motes are governed by two s 
>imple principles. First, each mote tries to move towards the mous 
>e cursor, and second each mote tries to move away from the averag 
>e mote position. Combined, we get this very natural looking behav 
>ior. 
102    </p>
103    <p>
104      This is done completely in W3C Standards–XHTML, SVG and Jav
>ascript–no flash or any vendor specific extensions. Currently, th 
>is will work in Mozilla Firefox version 1.5 and above. 
105    </p>
106    <pre>
107&lt;?xml version='1.0'?&gt;
108&lt;html xmlns="http://www.w3.org/1999/xhtml"
109        xmlns:svg="http://www.w3.org/2000/svg"&gt;
110 
111        &lt;style type='text/css'&gt;
112        &lt;![CDATA[
113                label, input
114                {
115                        width: 150px;
116                        display: block;
117                        float: left;
118                        margin-bottom: 10px;
119                }
120                label
121                {
122                        text-align: right;
123                        width: 75px;
124                        padding-right: 20px;
125                }
126                br
127                {
128                        clear: left;
129                }
130        ]]&gt;
131        &lt;/style&gt;
132 
133        &lt;body onload='update()'&gt;
134                &lt;svg:svg id='display' width='400' height='300'
>&gt; 
135                        &lt;svg:circle id='cursor' cx='200' 
136cy='150' r='7' fill='#0000ff' fill-opacity='0.5'/&gt;
137                &lt;/svg:svg&gt;
138 
139                &lt;p&gt;A swarm of motes, governed by two simple
> principles. 
140                First, each mote tries to move towards the cursor
>, and 
141                second each mote tries to move away from the aver
>age 
142                mote position.  Combined, we get this very natura
>l 
143                looking behavior.
144                &lt;/p&gt;
145 
146                &lt;p&gt;
147                This is done completely in W3C Standards–XHTML,
148                SVG and Javascript–no flash or any vendor specifi
>c 
149                extensions.  Currently, this will work in Mozilla
> Firefox 
150                version 1.5 and above.
151                &lt;/p&gt;
152 
153                &lt;p&gt;
154                (C) 2006 &lt;a id='emailme' href='#'&gt;Nick John
>son&lt;/a&gt; 
155 
156                &lt;script type='text/javascript'&gt;
157                &lt;![CDATA[
158                        // foil spam bots
159                        var email = '@riovia.net';
160                        email ='nick' + email;
161                        document.getElementById('emailme').href =
> 'mailto:'+email; 
162                ]]&gt;
163                &lt;/script&gt;
164                This software is free for you to use in any way w
>hatsoever, 
165                and comes with no warranty at all.
166                &lt;/p&gt;
167 
168                &lt;form&gt;
169                        &lt;label&gt;Number of motes:&lt;/label&g
>t; 
170                                &lt;input id='num_motes' value='5
>'/&gt; 
171 
172                                &lt;br/&gt;
173 
174                        &lt;label&gt;Max. Velocity:&lt;/label&gt;
175                                &lt;input id='max_velocity' value
>='15'/&gt; 
176                                &lt;br/&gt;
177 
178                        &lt;label&gt;Attraction to cursor:&lt;/la
>bel&gt; 
179                                &lt;input id='attract_cursor' val
>ue='6'/&gt; 
180                                &lt;br/&gt;
181 
182                        &lt;label&gt;Repulsion from peers:&lt;/la
>bel&gt; 
183                                &lt;input id='repel_peer' value='
>5'/&gt; 
184                                &lt;br/&gt;
185                &lt;/form&gt;
186        &lt;/body&gt;
187 
188        &lt;script type='text/javascript'&gt;
189        &lt;![CDATA[
190 
191                // Array of motes
192                var motes;
193 
194                // Get the display element.
195                function Display()
196                {
197                        return document.getElementById('display')
>; 
198                }
199 
200                // Determine dimensions of the display element.
201                // Return this as a 2-tuple (x,y) in an array
202                function Dimensions()
203                {
204                        // Our Rendering Element
205                        var display = Display();
206                        var width = parseInt( display.getAttribut
>eNS(null,'width') ); 
207                        var height = parseInt( display.getAttribu
>teNS(null,'height') ); 
208 
209                        return [width,height];
210                }
211 
212                // This is called by mouse move events
213                var mouse_x = 200, mouse_y = 150;
214                function OnMouseMove(evt)
215                {
216                        mouse_x = evt.clientX;
217                        mouse_y = evt.clientY;
218 
219                        var widget = document.getElementById('cur
>sor'); 
220                        widget.setAttributeNS(null,'cx',mouse_x);
221                        widget.setAttributeNS(null,'cy',mouse_y);
222                }
223                document.onmousemove = OnMouseMove;
224 
225                // Determine (x,y) of the cursor
226                function Cursor()
227                {
228                        return [mouse_x, mouse_y];
229                }
230 
231                // Determine average (x,y) of the swarm
232                function AverageMotePosition()
233                {
234                        if( !motes )
235                                return [0,0];
236 
237                        if( motes.length == 0 )
238                                return [0,0];
239 
240                        var i;
241                        var sum_x=0, sum_y=0;
242                        for(i=0; i&lt;motes.length; i++)
243                        {
244                                sum_x += motes[i].x;
245                                sym_y += motes[i].y;
246                        }
247 
248                        return [sum_x/motes.length, sum_y/motes.l
>ength]; 
249                }
250 
251                // A nicer, integer random
252                function Rand(modulo)
253                {
254                        return Math.round( Math.random() * (modul
>o-1)); 
255                }
256 
257                // Class Mote
258                function Mote()
259                {
260                        // Dimensions of drawing area.
261                        var dims = Dimensions();
262                        var width = dims[0], height = dims[1];
263 
264                        // Choose a random coordinate to start at
>. 
265                        this.x = Rand( width );
266                        this.y = Rand( height );
267 
268                        // Nil initial velocity.
269                        this.vx = this.vy = 0;
270 
271                        // A visual element---initially none
272                        this.elt = null;
273                }
274 
275                // Turn this into a class.
276                new Mote();
277 
278                // Mote::applyForce() -- Adjust velocity
279                // towards the given position.
280                // Warning: Pseudo-physics -- not really
281                // governed by any /real/ physical principles.
282                Mote.prototype.applyForce = function(pos, mag)
283                {
284                        if( pos[0] &gt; this.x )
285                                this.vx += mag;
286                        else if( pos[0] &lt; this.x )
287                                this.vx -= mag;
288 
289                        if( pos[1] &gt; this.y )
290                                this.vy += mag;
291                        else if( pos[1] &lt; this.y )
292                                this.vy -= mag;
293                }
294 
295                // Mote::capVelocity() -- Apply an upper limit
296                // on mote velocity.
297                Mote.prototype.capVelocity = function()
298                {
299                        var max = parseInt( document.getElementBy
>Id('max_velocity').value ); 
300 
301                        if( max &lt; this.vx )
302                                this.vx = max;
303                        else if( -max &gt; this.vx )
304                                this.vx = -max;
305 
306                        if( max &lt; this.vy )
307                                this.vy = max;
308                        else if( -max &gt; this.vy )
309                                this.vy = -max;
310                }
311 
312                // Mote::capPosition() -- Apply an upper/lower li
>mit 
313                // on mote position.
314                Mote.prototype.capPosition = function()
315                {
316                        var dims = Dimensions();
317                        if( this.x &lt; 0 )
318                                this.x = 0;
319                        else if( this.x &gt;= dims[0] )
320                                this.x = dims[0]-1;
321 
322                        if( this.y &lt; 0 )
323                                this.y = 0;
324                        else if( this.y &gt;= dims[1] )
325                                this.y = dims[1]-1;
326                }
327 
328                // Mote::move() -- move a mote, update the screen
>. 
329                Mote.prototype.move = function()
330                {
331                        // Apply attraction to cursor.
332                        var attract = parseInt( document.getEleme
>ntById('attract_cursor').value ); 
333                        var cursor = Cursor();
334                        this.applyForce(cursor, attract);
335 
336                        // Apply repulsion from average mote posi
>tion. 
337                        var repel = parseInt( document.getElement
>ById('repel_peer').value ); 
338                        var average = AverageMotePosition();
339                        this.applyForce(average, -repel);
340 
341                        // Add some randomness to the velocity.
342                        this.vx += Rand(3)-1;
343                        this.vy += Rand(3)-1;
344 
345                        // Put an upper limit on velocity.
346                        this.capVelocity();
347 
348                        // Apply velocity.
349                        var old_x = this.x, old_y = this.y;
350                        this.x += this.vx;
351                        this.y += this.vy;
352                        this.capPosition();
353 
354                        // Draw it.
355 
356                        if( this.elt === null )
357                        {
358                                var svg = 'http://www.w3.org/2000
>/svg'; 
359                                this.elt = document.createElement
>NS(svg,'line'); 
360                                this.elt.setAttributeNS(null,'str
>oke','green'); 
361                                this.elt.setAttributeNS(null,'str
>oke-width','3'); 
362                                this.elt.setAttributeNS(null,'str
>oke-opacity','0.5'); 
363                                Display().appendChild( this.elt )
>; 
364                        }
365 
366                        this.elt.setAttributeNS(null,'x1',old_x);
367                        this.elt.setAttributeNS(null,'y1',old_y);
368 
369                        this.elt.setAttributeNS(null,'x2',this.x)
>; 
370                        this.elt.setAttributeNS(null,'y2',this.y)
>; 
371                }
372 
373 
374                function update()
375                {
376                        // First call?
377                        if( !motes )
378                                motes = [];
379 
380                        // How many motes should there be?
381                        var num = parseInt( document.getElementBy
>Id('num_motes').value ); 
382                        if( num &lt; 0 )
383                                num = 0;
384 
385                        // Make sure we have exactly that many...
386                        // Too few?
387                        while( motes.length &lt; num )
388                                motes.push( new Mote() );
389                        // Or too many?
390                        if( num == 0 )
391                                motes = [];
392                        else if( motes.length &gt; num )
393                                motes = motes.slice(0,num-1);
394 
395                        // Move a random mote
396                        if( motes.length &gt; 0 )
397                                motes[ Rand( motes.length ) ].mov
>e(); 
398 
399                        // And do this again in 1/100 sec
400                        setTimeout('update()', 10);
401                }
402        ]]&gt;
403 
404        &lt;/script&gt;
405 
406&lt;/html&gt;
407</pre>
t411    <p>t100    <ul>
101      <li>Another example: <a href="en/SVG/Namespaces_Crash_Cours
 >e/Example">SVG:Namespaces Crash Course:Example</a>
102      </li>
412      http://svg-whiz.com/wiki/index.php?title=Inline_SVG103      <li>http://svg-whiz.com/wiki/index.php?title=Inline_SVG
104      </li>
413    </p>{{ wiki.languages( { "pl": "pl/SVG_w_XHTML_-_Wprowadzenie105    </ul>{{ wiki.languages( { "pl": "pl/SVG_w_XHTML_-_Wprowadzeni
>", "fr": "fr/Introduction_\u00e0_SVG_dans_HTML", "ja": "ja/SVG_In>e", "fr": "fr/Introduction_\u00e0_SVG_dans_HTML", "ja": "ja/SVG_I
>_HTML_Introduction" } ) }}>n_HTML_Introduction" } ) }}

Back to History