How to animate a vector path like it's being drawn, progressively? In other words, slowly show the path pixel by pixel.
I'm using Raphaël.js, but if your answer is not library specific—like maybe there's some general programming pattern for doing that kind of thing (I'm fairly new to vector animation)—it's welcome!
It's easy to do with straight paths, as easy as an example on that page::
path("M114 253").animate({path: "M114 253 L 234 253"});
But try to change code on that page, say, this way::
path("M114 26").animate({path: "M114 26 C 24 23 234 253 234 253"});
And you'll see what I mean. Path is certainly animated from it initial state (point "M114 26") to the end state (curve "C 24 23 234 253 234 253" starting on point "M114 26"), but not in a way specified in question, not like it's being drawn.
I don't see how animateAlong can do that. It can animate an object along a path, but how can I make this path to gradually show itself while object is being animated along it?
The solution?
(Via peteorpeter's answer.)
Seems like currently the best way to do it is via 'fake' dashes using raw SVG. For the explanation see this demo or this document, page 4.
How produce progressive drawing?
We have to use stroke-dasharray and stroke-dashoffset and know length of curve to draw.
This code draw nothing on screen for circle, ellipse, polyline, polygone or path:
<[element] style="stroke-dasharray:[curve_length],[curve_length]; stroke-dashoffset:[curve_length]"/>
If in animate element stroke-dashoffset decrease to 0, we get progressive drawing of curve.
<circle cx="200" cy="200" r="115"
style="fill:none; stroke:blue; stroke-dasharray:723,723; stroke-dashoffset:723">
<animate begin="0" attributeName="stroke-dashoffset"
from="723" to="0" dur="5s" fill="freeze"/>
</circle>
If you know a better way, please leave an answer.
Update (26 Apr. 2012): Found an example that illustrates the idea well, see Animated Bézier Curves.
Maybe someone is searching for an answer, like me for two days now:
// Draw a path and hide it:
var root = paper.path('M0 50L30 50Q100 100 50 50').hide();
var length = root.getTotalLength();
// Setup your animation (in my case jQuery):
element.animate({ 'to': 1 }, {
duration: 500,
step: function(pos, fx) {
var offset = length * fx.pos;
var subpath = root.getSubpath(0, offset);
paper.clear();
paper.path(subpath);
}
});
That did the trick for me, only by using RaphaelJS methods.
Here is a jsFiddle example as requested in the comments, http://jsfiddle.net/eA8bj/
Eureka! (Maybe - assuming you're comfortable stepping outside the friendly realm of Raphael into pure SVG land...)
You can use SVG keyTimes and keySplines.
Here's a working example:
http://www.carto.net/svg/samples/animated_bustrack.shtml
...and here's some potentially useful explanation:
http://msdn.microsoft.com/en-us/library/ms533119(v=vs.85).aspx
I'd like to offer an alternative, Raphael+JS-only solution that I have made substantial use of in my own work. It has several advantages over davidenke's solution:
Doesn't clear the paper with each cycle, allowing the animated path to coexist nicely with other elements;
Reuses a single path with Raphael's own progressive animation, making for smoother animations;
Substantially less resource intensive.
Here's the method (which could quite easily be retooled into an extension):
function drawpath( canvas, pathstr, duration, attr, callback )
{
var guide_path = canvas.path( pathstr ).attr( { stroke: "none", fill: "none" } );
var path = canvas.path( guide_path.getSubpath( 0, 1 ) ).attr( attr );
var total_length = guide_path.getTotalLength( guide_path );
var last_point = guide_path.getPointAtLength( 0 );
var start_time = new Date().getTime();
var interval_length = 50;
var result = path;
var interval_id = setInterval( function()
{
var elapsed_time = new Date().getTime() - start_time;
var this_length = elapsed_time / duration * total_length;
var subpathstr = guide_path.getSubpath( 0, this_length );
attr.path = subpathstr;
path.animate( attr, interval_length );
if ( elapsed_time >= duration )
{
clearInterval( interval_id );
if ( callback != undefined ) callback();
guide_path.remove();
}
}, interval_length );
return result;
}
And here are two samples of its usage on my site: one for Path Transformation, and the other for Progressive Lettering.
I've created a script for this: Scribble.js, based on this great dasharray/dashoffset technique.
Just instantiate it overs a bunch of SVG <path>s:
var scribble = new Scribble(paths, {duration: 3000});
scribble.erase();
scribble.draw(function () {
// done
});
--
NB: Full USAGE code here: https://gist.github.com/abernier/e082a201b0865de1a41f#file-index-html-L31
Enjoy ;)
Using "pathLength" attribute we can set virtual length to the path. From then we can use this virtual length in "stroke-dasharray".
So if we set "pathLength" to 100 units we then can set "stroke-dasharray" to "50,50" wich wuld be exactly 50%, 50% of the path!
There is one problem with this approach: the only browser that supports this attribute is Opera 11.
Here is example of smooth curve drawind animation without javascript or hardcoded length.(Works properly only in Opera 11)
Anton & Peteorpeter's solution sadly breaks down in Chrome when paths get complicated. It's fine for the bus map in that linked demo. Check out this animated "flower petals" jsfiddle I created, which draws correctly in FF10 and Safari5, but flickers uncontrollably in Chrome:
http://jsfiddle.net/VjMvz/
(This is all HTML and inline SVG, no javascript.)
I'm still looking for a non-Flash solution for this. AnimateAlong obviously won't cut it for what I'm doing. Raphael.js could work, though it threatens to turn into callback spaghetti really fast.
Davidenke, can you post a working jsfiddle with your solution? I just can't get it to work. I'm getting an error in Chrome 18 that nodes that are set to "display: none" with your ".hide" have no method 'getTotalLength'.
Unfortunately, as you seem to agree, you probably can't do this elegantly in Raphael.
However, if, by some stroke of %deity% you don't need to support IE for this particular feature, you could forgo the Raphael API and manipulate the SVG directly. Then, perhaps, you could rig a mask to ride along the path and reveal the line at a natural pace.
You could degrade gracefully in IE to simply show the path using Raphael, without animation.
i was just doing exactly this. The first thing i tried was Anton's solution but the performance sucks.
In the end the easiest way to get the result i wanted was to use the alternative "keyframe" syntax for the animate function.
draw the final path invisibly, then generate a whole bunch of key frames by using getSubpath in a loop.
create a new path that is visible and equals the first keyframe.
then do something like:
path.anmimate({ keyFrameObject, timeframe });
you shouldn't need a keyframe for every pixel that you want to draw. After playing around with the parameters, i found that a value of 100px per keyframe worked for the complexity/size of what i was trying to "draw"
Just an update to this, you could try Lazy Line Painter
Have you tried Raphael's animateAlong? You can see it in action on a demo page.
Alright, here's my thoughts on this… The solution's too far from ideal.
To gradually show the path mean we should show it, like, dot by dot. And vector paths consist not of dots, but of curves, so it appears to me there's no ‘natural’ way to gradually ‘draw’ the path in vector graphics. (Though I'm fairly new to this and may be mistaken.)
The only way would be to somehow convert a path to a number of dots and show them one by one.
Currently my workaround is to draw a path, make it invisible, break it into a number of subpaths, and show that subpaths one by one.
This isn't hard to do with Raphael, but it's not elegant either, and quite slow on a large paths. Not accepting my answer, hoping there's a better way…
Related
I'm drawing a simple interpolated line using D3.js (output as path). However, I want part of the path to have a dashed stroke if a boolean in a data point is set to true:
Link to image
An easy solution would be to just draw it with <line> segments instead - but that way I lose the interpolation.
Then I found an example from mbostock, showing how to draw a gradient along a interpolated path. I modified it to just draw transparent path fills whenever the boolean was set to true and white fills when false - while my old path is all dashed.
That works (queue the above screenshot) - but by adding around thousand path elements to the DOM contra having only a single path.
It's not desirable with that many DOM elements, especially since I'm going to make more curves and the site needs to be mobile optimized. Am I missing a much simpler solution?
Wouldn't mind a modified version of mbostock's example doing the heavy calculations in advance, as long as the DOM output is simple.
Thanks!
I prepared this example for another SO question. Screenshot is here:
I think you have enough material there to devise a solution that fits your needs.
Take a look also at this page:
SVG Path Styling
You could use stroke-dasharray to add dashes in the stroke of the generated path in the right places. That would entail finding the proper dash lengths. This can be done by calling pathElm.getPathLength() on the path up to the point where you want it to start being dashed, and to where you want it to end.
Let's say path A that is the part that is before the dashes should start. Set the d attribute with that part and call getPathLength() on it. Let's call this length a.
Append the the part of the path that should be dashed to the d attribute, then call getPathLength() again. Let's call this length b.
Create a new path element with the remaining part of the path, then call getPathLength() on that. Let's call this length c.
Construct a stroke-dasharray property string something like this:
var a = getPathLengthA();
var b = getPathLengthB();
var c = getPathLengthC();
var dasharray = a + " ";
for(var usedlen = 0; usedlen < (b-a); ) {
dasharray += "5 10 "; // just whatever dash pattern you need
usedlen += 15; // add the dash pattern length from the line above
}
dasharray += c;
pathElement.style.strokeDasharray = dasharray;
Here's a static example of that.
I'm trying to add an indicator to my vertical gauge but the format of the indicator is like a triangle, but I want it a large line.
This is JSFIDDLE example.
The code :
require(['dojo/parser', 'dojox/dgauges/components/default/VerticalLinearGauge','dojox/dgauges/RectangularRangeIndicator', 'dojo/domReady!'], function (parser, VerticalLinearGauge) {
parser.parse();
var ri = new dojox.dgauges.RectangularRangeIndicator();
ri.set("start",0 );
ri.set("value", 30);
ri.set("startThickness",100);
ri.set("endThickness",100);
gauge.getElement("scale").addIndicator("ri", ri, false);
});
This is a bug, it will be fixed in next releases (1.8.x and 1.9).
See https://github.com/dmandrioli/dgauges/issues/15
As a workaround, you can redefine the bad method like this:
myRangeIndicator._defaultVerticalShapeFunc =
function(indicator, group, scale, startX,
startY, endPosition, startThickness, endThickness,
fill, stroke){ ... }
See this workaround in action at http://jsfiddle.net/BFPuL/5/
I think that the properties are startThickness and endThickness (no "stroke" at the end). However, I still don't get one solid line when setting these properties to equal values like one would expect. It seems as though something odd (perhaps a bug) is happening with the way that the startThickness property is handled.
This problem has me interested, so I'll try to set aside some time later to dig into the source to see what the real issue is, but for now I can offer you a dirty workaround. The RectangularRangeIndicator is drawn using the dojox/gfx module, and the outline of the indicator drawn is controlled by the stroke property. So, if you want, you can do something like:
var ri = new dojox.dgauges.RectangularRangeIndicator();
ri.set("start",0 );
ri.set("value", 30);
ri.set("startThickness", 0);
ri.set("endThickness", 0);
ri.set("stroke", {color: "red", width: 2.5});
ri.set("paddingLeft", 7); // Default is 10, set this to whatever works for you.
This will appear to draw straight line (which is really the border of an extremely thin shape). Check out how it looks in a real example. Again, I understand that this is not the best solution since it is more of a dirty trick, but it is a way around what appears to be a bug in the code that renders a range indicator.
My goal:
Move/animate an image along a path like the drawing below (Could be connecting bezier curves).
Must work in IE7+, don't what to build multiple solutions.
I can pause/resume the moving image.
The image will keep moving along the path (repeat).
What I have considered
CANVAS: not supported in IE7+8, haven't tested explorercanvas yet! Foresee some z-index issues.
SVG, not supported in IE7+8.
jQuery.path, a plugin that extends the jQuery animate function. Can't figure out the resume part and I want to use CSS transforms when supported.
My plan
Animate the image with CSS 3D transform, CSS 2d transform or jQuery.animate (what supported) and requestAnimationFrame.
Calculate all the coordinates and simple move the image pixel by pixel.
My question
Does my plan sound like madness? Better suggestions?
Do you foresee some performance issues? I might end up with 5K or 10K coordinates.
Do you know a smart way, a program, a function or anything similar to calculate all the coordinates?
There's a tiny script (SVG based), just for animation which isn't in straight lines,
called pathAnimator (2kb), It's very very small and very efficient.
No jQuery required.
For example:
var path = "M150 0 L75 200 L225 200 Z"; // an SVG path
pathAnimator = new PathAnimator( path ), // initiate a new pathAnimator object
speed = 6, // seconds that will take going through the whole path
reverse = false, // go back or forward along the path
startOffset = 0, // between 0% to 100%
easing = function(t){ t*(2-t) }; // optional easing function
pathAnimator.start( speed, step, reverse, startOffset, finish, easing);
function step( point, angle ){
// do something every "frame" with: point.x, point.y & angle
}
function finish(){
// do something when animation is done
}
(can even get more efficient using fastdom)
I would recommend you to use GSAP : http://www.greensock.com/get-started-js/
With that you can handle timelines, and here is a bezier plugin : http://api.greensock.com/js/com/greensock/plugins/BezierPlugin.html
regards
I don't understand how to rotate my object at a certain point. This is the javascript I have
// create needle
var rsr = Raphael('rsr', '320', '240');
var needle = rsr.path("m 156.74443,870.84631 -2.26177,119.38851
4.38851,0 z"); needle.attr({id: 'needle',parent: 'layer1',fill:
'#ff6600',stroke: '#000000',"stroke-width": '0.61',"stroke-linecap":
'butt',"stroke-linejoin": 'miter',"stroke-miterlimit": '4',"stroke-
opacity": '1',"stroke-dasharray": 'none'});
needle.rotate(0);
needle.transform("t0,-812.36218").data('id', 'needle');
// get needle bounding box
var needleBox = needle.getBBox();
// calculate rotation point (bottom middle)
var x_rotate_point = needleBox.x + (needleBox.width/2);
var y_rotate_point = needleBox.y + needleBox.height;
// rotate needle
needle.attr({rotation: 0}).animate({transform:"r45,"+x_rotate_point
+","+y_rotate_point}, 6000);
// Creates circle at rotation point
var circle = rsr.circle(x_rotate_point, y_rotate_point, 10);
circle.attr("fill", "#f00");
circle.attr("stroke", "#fff");
I have created a dummy circle to check if my coordinates of my center point is correct
and it is, but it doesn't rotate around that point :-/
When I created gauges in different frameworks that always seemed the way to go, but that logic doesn't seem to translate well into Raphael 2.0.
I did google for it and found some entries but the problem seems it is for
older versions which doesn't translate well because a lot of
stuff got changed or is deprecated.
You are setting the center of rotation correctly, but there are some other things going on which are causing some confusion. I was able to get this to work by changing the animation target to:
{transform: needle.attr("transform") + "R45,"+x_rotate_point+","+y_rotate_point}
I think the way you had it, the animation was gradually removing the previous translation while also doing the rotation. This addition allows it to accumulate the transformations. Also, note that I had to switch the 'r' to 'R'. It is not really clear to me what the small 'r' is doing in this example.
Anyway, here is a working demo.
Btw, I also commented out a few rotations that didn't seem to be doing anything.
I've been playing around with canvas a lot lately. Now I am trying to build a little UI-library, here is a demo to a simple list (Note: Use your arrow keys, Chrome/Firefox only)
As you can tell, the performance is kinda bad - this is because I delete and redraw every item on every frame:
this.drawItems = function(){
this.clear();
if(this.current_scroll_pos != this.scroll_pos){
setTimeout(function(me) { me.anim(); }, 20, this);
}
for (var i in this.list_items){
var pos = this.current_scroll_pos + i*35;
if(pos > -35 && pos < this.height){
if(i == this.selected){
this.ctx.fillStyle = '#000';
this.ctx.fillText (this.list_items[i].title, 5, pos);
this.ctx.fillStyle = '#999';
} else {
this.ctx.fillText (this.list_items[i].title, 5, pos);
}
}
}
}
I know there must be better ways to do this, like via save() and transform() but I can't wrap my head around the whole idea - I can only save the whole canvas, transform it a bit and restore the whole canvas. The information and real-life examples on this specific topic are also pretty rare, maybe someone here can push me in the right direction.
One thing you could try to speed up drawing is:
Create another canvas element (c2)
Render your text to c2
Draw c2 in the initial canvas with the transform you want, simply using drawImage
drawImage takes a canvas as well as image elements.
Ok, I think I got it. HTML5 canvas uses a technique called "immediate mode" for drawing, this means that the screen is meant to be constantly redrawn. What sounds odd (and slow) first is actually a big advantage for stuff like GPU-acceleration, also it is a pretty common technique found in opengl or sdl. A bit more information here:
http://www.8bitrocket.com/2010/5/15/HTML-5-Canvas-Creating-Gaudy-Text-Animations-Just-Like-Flash-sort-of/
So the redrawing of every label in every frame is totally OK, I guess.