...

View Full Version : javascript to animate svg



clearab
01-12-2012, 06:31 AM
I'm new to JavaScript, and this forum so please forgive any improprieties. What I'm trying to do is fairly simple. I have a script that creates some SVG rectangles. I want to be able to click a button and have two rectangles switch places, moving along a curve to do so. This is part of a prototype for a larger product. I've included the relevant code pieces below, and I've also included the whole .html file as an attachment if you prefer. I feel like I'm on the right track, but I cannot figure out why it is not working. I "believe" the problem is when I create the animateA and animateB elements (syntax perhaps?). Please let me know if this is not enough information, as I've been staring at it for so long I seem to have lost perspective. Thanks for any help.



var svgNS = "http://www.w3.org/2000/svg";
var xlinkNS = "http://www.w3.org/1999/xlink";
var animateDur = "1s";

function swap(a,b) {
//this section handles moving the actual elements of the array
//rectArray is an array of integer values that represent the height of the rectangles
var temp = rectArray[a];;
rectArray[a]=rectArray[b];
rectArray[b]=temp;
//this section is for the animation (will probably be its own function
//for the final version
//get the elements
var aRect = document.getElementById("rect_" + a);
var bRect = document.getElementById("rect_" + b);
//get the element coordinates, bY isn't needed, as it
//is the same as bX
var aX = aRect.getAttributeNS(null,"x");
var aY = aRect.getAttributeNS(null,"y");
var bX = bRect.getAttributeNS(null,"x");
//calculate the x distance from a to b and from b to a
//to use in the bezier curve path
var aToBx = bX - aX;
var bToAx = aX - bX;
//calculate the halfway point to use in the bezier curve
var qA = Math.floor(aToBx/2);
var qB = Math.floor(bToAx/2);
//create the path strings:
//should be M startX startY q midpointX midpointY endX endY
//notice that endX and endY are with respect to the startX and startY
var pathAtoB = "M" + aX + " " + aY + " q " + qA + " 30 " + aToBx + " " + aY;
var pathBtoA = "M" + bX + " " + bY + " q " + qB + " 30 " + bToAx + " " + aY;
//create the animation element for rectangle A
animateA = document.createElementNS(svgNS, "animateMotion");
animateA.setAttributeNS(null,"path",pathAtoB);
animateA.setAttributeNS(null,"dur",animateDur);
//append it to the rectangle
aRect.appendChild(animateA);
//create the animation element for rectangle B
animateB = document.createElementNS(svgNS, "animateMotion");
animateB.setAttributeNS(null,"path",pathBtoA);
animateB.setAttributeNS(null,"dur",animateDur);
//append it to the rectangle
bRect.appendChild(animateB);
//change the id's of the rectangles to reflect their new
//positions
aRect.setAttributeNS(null,"id","rect_" + b);
bRect.setAttributeNS(null,"id","rect_" + a);
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum