I have an SVG path like this:
<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" version="1.1" baseProfile="full">
<path d="M47.16,66.38c0.62,1.65-0.03,2.93-0.92,4.28c-5.17,7.8-8.02,11.38-14.99,18.84c-2.11,2.25-1.5,4.18,2,3.75c7.35-0.91,28.19-5.83,40.16-7.95" style="fill:none;stroke:black;stroke-width:2" />
</svg>
I can render the path but can't seem to find a way to make the path animate so that it looks like it is "being draw" as if with pencil. The animate
node works for single coords but not for paths.
I will eventually end up using this animation in an iPhone app either with a parser or with a UIWebView.
Try animating the 'stroke-dashoffset' (note that you need a matching 'stroke-dasharray' with it), see this example. The length of the path that needs to be computed to be able to use this successfully can be fetched via script like:
var pathlength = yourPathElm.getTotalLength()
View source on the example to see how it's done.
I tried for a long while to do this without having to add extra scripts to the header (that I have no idea of javascript didn't help), so here's the solution:
<path d="..." stroke-dasharray="">
<animate attributeName="stroke-dashoffset" from="" to="0" dur="1s" begin="0s"
onload="var length = parentNode.getTotalLength();
parentNode.setAttribute('stroke-dasharray',length+','+length);
this.setAttribute('from',length)" />
</path>
I added extra line breaks for readability here.
This is legal in SVG (although not in HTML) because the svg:animate
element allows onload
, which most HTML elements do not.
Once you've rendered your SVG path, to make it look like it's being drawn with a pencil, you could simply cover it all with an opaque layer, and then animate the movement of this layer along the path.
To find the CGPath
along which you'll move the layer you can use this library:
https://github.com/arielelkin/PocketSVG
This will parse the SVG data into a UIBezierPath. Then:
SvgToBezier *myBezier = [[SvgToBezier alloc] initFromSVGPathNodeDAttr:@"M176.17,369.617c0,0,335.106-189.361,214.894,38.298s129.787,282.978,178.723,42.553C618.724,210.042,834.681,87.702,790,307.915" rect:CGRectMake(0,0,1024,768)];
UIBezierPath *myPath = myBezier.bezier;
CAKeyframeAnimation *mySVGPathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
bounceAnimLeft.duration = 3;
bounceAnimLeft.path = myPath.CGPath;
[myObjectToMove.layer addAnimation:mySVGPathAnimation forKey:@"pathAnimation"];