Creating dynamic and visually appealing graphics is a key aspect of modern web development. One powerful tool for this purpose is SVG (Scalable Vector Graphics), a language for describing two-dimensional graphics in XML. When combined with jQuery, SVG can be used to create animated charts that enhance user experience. In this comprehensive guide, we will show you how to draw an animated pie chart using jQuery and SVG.
What is SVG?
SVG is a versatile language used to define vector-based graphics that can be scaled indefinitely without loss of quality. It’s ideal for creating complex graphics like charts, diagrams, and interactive visuals. SVG graphics are easily manipulated using JavaScript, making it a perfect companion for jQuery, which simplifies client-side scripting.
Setting Up the Environment
To start using jQuery with SVG, you need to include jquery.svg.js along with jQuery itself. For this example, we will use jquery-1.11.1.js and jquery.svg.js. These files can be downloaded and included in your project.
Here is the basic HTML setup:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-1.11.1.js"></script>
<script src="js/jquery.svg.js"></script>
</head>
<body>
<div id="svgpiechart" style="border:1px solid;width:400px;height:400px;"></div>
<script>
jQuery.noConflict();
jQuery(document).ready(function() {
var center_x = 175;
var center_y = 175;
var radius_x = 150;
var radius_y = 60;
var drawPercent = 60;
var startFromDegree = 90;
draw_pie_chart(center_x, center_y, radius_x, radius_y, drawPercent, startFromDegree);
});
function draw_pie_chart(center_x, center_y, radius_x, radius_y, drawPercent, startFromDegree) {
var obj = jQuery("#svgpiechart");
jQuery(obj).svg();
var svg = jQuery(obj).svg('get');
var g = svg.group({stroke: '#d42026'});
var totalDegD = 360 / 100 * drawPercent;
var i = startFromDegree;
var atTo = i + totalDegD;
var stop = 0;
var timer = window.setInterval(function() {
for (var s = 0; s < 4; s++) {
if (stop === 1) return;
var d = i;
var a = d * Math.PI / 180;
var x = center_x + radius_x * Math.cos(a);
var y = center_y + radius_y * Math.sin(a);
svg.line(g, center_x, center_y, x, y, {strokeWidth: 5});
i++;
if (i >= atTo) {
window.clearInterval(timer);
stop = 1;
return;
}
}
}, 1);
}
</script>
</body>
</html>
Understanding the Code
Initialization
- The jQuery library and the
jquery.svg.jsplugin are included in the HTML head. - A
divwith the IDsvgpiechartis set up to hold the pie chart.
Document Ready Function:
- Inside the
jQuery(document).readyfunction, we initialize the center coordinates of the pie chart and the radii for the x and y axes. This allows us to draw both circular and elliptical shapes. drawPercentspecifies the percentage of the pie chart to be filled.startFromDegreesets the starting point of the fill.
Drawing the Pie Chart:
- The
draw_pie_chartfunction is defined to handle the drawing logic. jQuery("#svgpiechart").svg()initializes the SVG element.- The drawing is performed by calculating the end coordinates for the lines that form the sectors of the pie chart using trigonometric functions.
- An interval is set to animate the drawing process by incrementing the angle degree by degree until the specified percentage of the chart is filled.
Customizing the Pie Chart
Center Position:
- Adjust
center_xandcenter_yto change the position of the pie chart on the screen.
Shape:
- Use the same value for
radius_xandradius_yfor a circular pie chart. Different values create an elliptical shape.
Percentage Fill:
- Modify
drawPercentto change the fill percentage of the pie chart.
Start Angle:
- Change
startFromDegreeto set the angle from which the fill starts.
Advanced Customization
Adding Colors:
- Customize the
strokeattribute in thesvg.groupmethod to change the color of the pie chart sectors.
Multiple Sectors:
- To draw multiple sectors, modify the
draw_pie_chartfunction to accept an array of percentages and loop through them, adjusting thestartFromDegreeaccordingly for each sector.
Interactive Features:
- Add event listeners to make the chart interactive. For example, you can highlight a sector on hover or display additional information.