SVG Animation and JavaScript - Part 2 of Chapter 7 from Perl Graphics Programming (2/4)
[previous] [next] |
Perl Graphics Programming, Chapter 7: Creating SVG with Perl
Creating a Bouncing Ball
The example in this section creates a simple bouncing ball. We use the XML::Writer module to create the SVG output. The make_bounce_path( ) function returns a properly formatted path data string. The $ground variable indicates the y coordinate of the "ground line" off which the ball bounces. The bounce path follows the positive part of a sine wave.
Here's the first part of the code:
#!/usr/bin/perl -w
# The bouncing ball.
use strict;
use XML::Writer; # Used to write the SVG output
my ($width, $height) = (300, 300);
my $writer = XML::Writer->new( );
$writer->setDataMode(1); # Auto insert newlines
$writer->setDataIndent(2); # Auto indent
$writer->startTag('svg',
height => $height,
width => $width,
'xmlns:xlink' => 'http://www.w3.org/1999/Xlink');
The circle is in the <circle></circle> format (rather than as an empty tag). It contains two animation tags. The <animateMotion> tag causes the circle to move along a path. The <animate> tag causes the radius of the ball to be increased over the course of the animation.
$writer->startTag('circle',
id => 'ball',
r => 10,
fill => '#FF0000');
$writer->emptyTag('animateMotion',
calcMode=> 'spline',
dur => "10s",
path => make_bounce_path(300, 200, 4),
repeatCount => "indefinite");
$writer->emptyTag('animate',
attributeName => "r",
from => 10,
to => 50,
dur => "10s",
repeatCount => "indefinite"
);
$writer->endTag('circle');
$writer->endTag('svg');
The make_bounce_path( ) function returns a properly formatted SVG path data string. The parameters are the x axis for the sine wave (the "ground" off which the ball bounces), the height of the bounce, and the number of bounces. The sin( ) function returns a value in radians; multiply by 2p to convert to a number in the range -1 to 1. With each bounce, the ground is moved up to take into account the changing radius of the ball, which varies from 10 to 50 pixels over the course of the animation.
sub make_bounce_path {
my ($ground, $bounce_height, $bounces) = @_;
my $pi = atan2(1,1) * 4;
my $points = "M0,$height ";
my $y;
for (my $x=1; $x < $width; $x+=5) {
$y = int($ground - abs(($bounce_height *
sin(($x/($width*2/$bounces)) * 2 * $pi))));
$points .= "L$x,$y ";
$ground -= 40/($width/5);
$height -= 40/($width/5);
}
return $points;
}
Figure 7-2 shows the bouncing ball with the animation path highlighted.

Figure 7-2. A bouncing ball, the canonical animation example
[previous] [next] |
Created: February 19, 2003
Revised: February 19, 2003
URL: http://webreference.com/programming/perl/chap7/2/2.html

Find a programming school near you