D3/Raphael js draws 1000+ animated circle with slow fps - javascript

I wrote script on Raphael JS v2.1 that draws 1000+ circles and many paths. Circles are animated along that paths and then removed. At ~100 circles fps is 40. At 1000+ fps is 1-10. Code example:
var r = Raphael("diagram", "100%", "100%");
setInterval(function () {
r.moveCircle(lines[Math.floor(Math.random() * 20)]);
}, 100);
Raphael.fn.moveCircle = function (path) {
var circle = this.circle(0, 0, 4).attr({fill: '#000'});
circle.animateAlong({
path: path,
duration: 1000
},
function() {
circle.remove();
});
};
Raphael.el.animateAlong = function (params, props, callback) {
var element = this,
paper = element.paper,
path = params.path,
rotate = params.rotate,
duration = params.duration,
easing = params.easing,
debug = params.debug,
isElem = typeof path !== 'string';
element.path =
isElem
? path
: paper.path(path);
element.pathLen = element.path.getTotalLength();
element.rotateWith = rotate;
element.path.attr({
stroke: debug ? 'red' : isElem ? path.attr('stroke') : 'rgba(0,0,0,0)',
'stroke-width': debug ? 2 : isElem ? path.attr('stroke-width') : 0
});
paper.customAttributes.along = function(v) {
var point = this.path.getPointAtLength(v * this.pathLen),
attrs = {
cx: point.x,
cy: point.y
};
this.rotateWith && (attrs.transform = 'r'+point.alpha);
return attrs;
};
if(props instanceof Function) {
callback = props;
props = null;
}
if(!props) {
props = {
along: 1
};
} else {
props.along = 1;
}
var startAlong = element.attr('along') || 0;
element.attr({along: startAlong}).animate(props, duration, easing, function() {
!isElem && element.path.remove();
callback && callback.call(element);
});
};
QUESTIONS:
1) is it possible to improve performance/speed/fps on Raphael JS?
2) on d3.js will fps be beter? what about 10,000+ animated circles?
3) is there any solutions to visualise 10,000+ animated circles along paths with good fps?

The likely bottleneck is DOM manipulation (adding / removing nodes, editing attributes etc), so d3 will have the same problem. Using canvas instead of SVG (particularly with a WebGL context) will be much faster if you have a lot of things to draw.
Ways you could speed things up while sticking with SVG:
Reuse DOM nodes instead of removing them and adding new ones
Define the animations ahead of time using CSS.

Another way to animate circles along a path is to use stroke-dasharray, stroke-dashoffset and stroke-linecap:round. Any zero-length dash will render as a circle. You can then use stroke-dashoffset to move the circles along the path. This only works with a single circle radius though, controlled via stroke-width.
The upside of this approach is that you may be able to eliminate a bunch of circle elements.

Related

Does the Fabric.js Path Array have a size limit?

I am trying to plot a line graph using Fabric.js. The fabric.Path seems the way to go but it stops drawing after 8 segments.
I've tried loops and individually coding each segment and it always stops drawing after 8 segments
const canvas = Controller.Canvas;
line = new fabric.Path('M 90 104', { stroke: 'black', fill: '' });
lastLeft = 90;
for (i = 1; i < 20; i++) {
lastLeft += 20;
line.path[i] = ['L', lastLeft, 104];
}
canvas.add(line);
I would expect the code to draw a line of 20 segments. It stops at 8. The canvas is plenty large enough.
Looking at the fabric.js code, Line's path property is not really supposed to be modified like that - it's more of an internal property. After the path is parsed from the path data passed into the constructor, fabric calculates the Line's dimensions and position, which it then uses during a render call. This means that if you've modified path after constructor is run, you're going to end up with wrong dimensions, hence the missing lines, etc.
There is a way to make fabric re-calculate dimensions, although it uses a private call. Which means that it could change between fabric versions (the snippet below works with 3.4.0) and is therefore not recommended, unless you really want to mess with path for some reason:
const canvas = new fabric.Canvas('c')
const initialX = 10
const initialY = 10
const line = new fabric.Path(`M ${initialX} ${initialY}`, { stroke: 'black', fill: '' })
for (let i = 1; i < 20; i++) {
line.path[i] = ['L', initialX + i * 20, initialY + Math.pow(i, 2)]
}
/* WARNING: Hacky stuff start */
fabric.Polyline.prototype._setPositionDimensions.call(line, {})
/* Hacky stuff end */
canvas.add(line)
body {
background: ivory;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.min.js"></script>
<canvas id="c" width="500" height="400"></canvas>

Negative coordinates in a grid based game

I have written a small 2D game in javascript that uses a grid where the player starts at position [0,0] and can move an almost infinite distance in either direction.
Now I want to implement A* pathfinding, but I'm having some problems finding the best way to store the world with all it's different obstacles, enemies and terrain. This is what I have tried or thought about so far.
Array of arrays
Here I store the world in an array of arrays [x][y].
var world = [[]];
world[312][11] = 0;
world[312][12] = 0;
world[312][13] = 1;
world[312][14] = 1;
...
This works great with A* pathfinding! It's easy and very fast to access a specific coordinate and populate the world. In the example above I just store passable (0) or impassable (1) terrain, but I can store pretty much whatever I want there. However, this doesn't work very well with negative coordinates like if my players is at [-12][-230]. Negative keys in a javascript array isn't actually part of the array, they won't be included in world.length or world[3].length and from what I understand, it's overall bad practice and might have some impact on the performance as well. I read somewhere that if you are using negative keys in your array, you are doing it wrong.
I would still not pass the entire world into the A* function for obvious reasons. Just a small part close to my player, but the coordinates would correspond to the positions in the array which is easy to work with.
A separate array of arrays just for A* pathfinding
This is where I'm at right now. I have a separate 50x50 grid called pathMap = [[]], that is only used for pathfinding.
var pathMap = [[]];
pathMap[0][0] = 0;
pathMap[0][1] = 0;
pathMap[0][2] = 1;
pathMap[0][3] = 1;
...
It starts at pathMap[0][0] and goes to pathMap[50][50] and is working as an overlay on my current position where I (as the player) will always be in the center position. My real coordinates may be something like [-5195,323], but it translates to pathMap[25][25] and everything close to me is put on the pathMap in relation to my position.
Now this works, but it's a huge mess. All the translations from one coordinate to another back and forth makes my brain hurt. Also, when I get the path back from A*, I have to translate each step of it back to the actual position my element should move to in the real world. I also have to populate the same object into 2 different grids every update which hurts performance a bit as well.
Array of objects
I think this is where I want to be, but I have some issues with this as well.
var world = [];
world[0] = { x: -10, y: 3, impassable: 0 };
world[1] = { x: -10, y: 4, impassable: 0 };
world[2] = { x: -10, y: 5, impassable: 1 };
world[3] = { x: -10, y: 6, impassable: 1 };
...
Works great with negative x or y values! However, it's not as easy to find for instance [10,3] in this array. I have to loop through the entire array to look for an object where x == 10 and y == 3 instead of the very easy and fast approach world[10][3] in the first example. Also, I can't really rely on the coordinates being in the right order using this version, sorting becomes harder, as does other things that was a lot easier with the array of arrays.
Rebuild the game to always be on the positive side
I would prefer not to do this, but I have considered placing the players starting position at something like [1000000,1000000] instead, and making negative coordinates off limits. It seems like a failure if I have to remove the vision I have of endlessness just to make the pathfinding work with less code. I know there will always be some upper or lower limits anyways, but I just want to start at [0,0] and not some arbitrary coordinate for array related reasons.
Other?
In javascript, is there another option that works better and is not described above? I'm very open to suggestions!
Is there a best practice for similar cases?
You have three coordinates system you must distinguish :
the world coordinates.
the world model / path-finding (array) coordinates.
the screen coordinates.
The screen coordinates system depends upon :
the viewport = the canvas. (width, height in pixels).
a camera = (x,y) center in world coordinates + a viewWidth (in world coordinates).
To avoid headaches, build a small abstraction layer that will do the math for you.
You might want to use Object.defineProperty to define properties, that will provide a fluent interface.
var canvas = ... ;
var canvasWidth = canvas.width;
var canvasHeigth = canvas.heigth;
var world = {
width : 1000, // meters
height : 1000, // meters
tileSize : 0.5, // height and width of a tile, in meter
model : null, // 2D array sized ( width/tileSize, XtileSize )
};
// possibles world coordinates range from -width/2 to width/2 ; - height/2 height/2.
var camera = {
x : -1,
y : -1,
viewWidth : 10, // we see 10 meters wide scene
viewHeight : -1 // height is deduced from canvas aspect ratio
};
camera.viewHeight = camera.viewWidth * canvasWidth / canvasHeight ;
Then your character looks like :
// (x,y) is the center of the character in centered world coordinates
// here (0,0) means (500,500) world coords
// (1000,1000) array coords
// (320, 240) screen coords in 640X480
function /*Class*/ Character(x, y) {
var _x=x;
var _y=y;
var _col=0;
var _row=0;
var _sx=0.0;
var _sy=0.0;
var dirty = true;
Object.defineProperty(this,'x',
{ get : function() {return _x; }
set : function(v) { _x=v;
dirty=true; } });
Object.defineProperty(this,'x',
{ get : function() {return _y; }
set : function(v) { _y=v;
dirty=true; } });
Object.defineProperty(this,'col',
{ get : function() {
if (dirty) updateCoords();
return _col; } });
Object.defineProperty(this,'row',
{ get : function() {
if (dirty) updateCoords();
return _row; } });
Object.defineProperty(this,'sx',
{ get : function() {
if (dirty) updateCoords();
return _sx; } });
Object.defineProperty(this,'sy',
{ get : function() {
if (dirty) updateCoords();
return _sy; } });
function updateCoords() {
_row = ( ( _x + 0.5 * world.width )/ world.tileSize ) | 0 ;
_col = ( ( _x + 0.5 * world.height )/ world.tileSize ) | 0 ;
_sx = canvasWidth * ( 0.5 + ( _x - camera.x ) / camera.viewWidth ) ;
_sy = canvasHeight * ( 0.5 + ( _y - camera.y ) / camera.viewHeight ) ;
dirty = false;
}
}

Javascript canvas animation. Moving, growing and fading object

Working on a project and cannot seem to get my animation right. I will not be showing the code because it simply doesn't work but it would be cool if someone were to give me a few pointers on how to animate a cloud of smoke moving upwards while slowly fading and increasing in size.
This effect should technically repeat once the y value reaches 0 i.o.w. the cloud reaches the top of the canvas.
What I need to know is how do I animate this, and which methods do I use. This is a kind of a self learning assignment.
Thanks in advance.
Here is a Plunker example of sprites growing in size and fading in transparency.
It is done using Pixi.js which actually renders in webgl with a canvas fallback. It should be possible to take the algorithm and apply it to raw canvas (although it would take some work).
var insertAfter = function(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var range = function(aCount) {
return new Array(aCount)
}
function main() {
var el_main = document.getElementById("animation_main");
var el_div = document.createElement('div');
el_div.setAttribute('id', 'main_stage');
insertAfter(el_div, el_main);
renderer = PIXI.autoDetectRenderer(300, 300, {
transparent: true,
antialias: true
});
el_div.appendChild(renderer.view);
window.stage = new PIXI.Container();
window.stage.x = 0;
window.stage.y = 0;
renderer.render(window.stage);
var s = [];
for (x of range(400)) {
tCircle = new PIXI.Graphics();
tCircle.beginFill(0x000000, 1);
tCircle.s = (Math.random() * 2) + 1;
tCircle.drawCircle(0, 0, 5 - tCircle.s);
tCircle.x = Math.random() * 300
tCircle.y = (Math.random() * 50) + 20
tCircle.endFill();
s.push(tCircle);
window.stage.addChild(tCircle)
}
window.t = 0
animate = function(t) {
d = t - window.t
window.t = t
//Animation Start
for (n in s){
s[n].x += ((s[n].s / 25) * d)
s[n].alpha = 1 - s[n].x / 300
s[n].scale.x = 1 - s[n].alpha
s[n].scale.y = 1 - s[n].alpha
if (s[n].x > 300) {
s[n].x = 0
s[n].y = (Math.random() * 50) + 20
}
}
renderer.render(window.stage)
//Animation End
requestAnimationFrame(animate);
}
requestAnimationFrame(animate)
}
document.addEventListener("DOMContentLoaded", function(e){
main();
});
At the moment all of the tweening is linear ... it might look more realistic with a logarithmic or exponential tween ... but for simplicity i just left it as linear.
Jakob Jenkov has done a really nice on-line book about canvas here:
http://tutorials.jenkov.com/html5-canvas/index.html
Since yours is a learning experience, I would just point you towards:
The basic workflow of html5 Canvas: Anything drawn on the canvas cannot be altered, so all canvas animation requires repeatedly doing these things in an animation loop: (1) clearing the canvas, (2) calculating a new position for your objects, and (3) redrawing the objects in their new positions.
Animations: requestAnimationFrame as a timing loop: http://blog.teamtreehouse.com/efficient-animations-with-requestanimationframe
Transformations: Canvas gives you the ability to scale, rotate and move the origin of its drawing surface.
Styling: Canvas provides all the essential styling tools for drawing--including globalAlpha which sets opacity.

How to paint over a complex object

I do have a fairly complex figure painted on canvas. (~ 1000 polygons). The repainting time for all of them is about 1 sec (very slow). Now I need to let user move over that figure and display a vertical and horizontal lines (cross hairs) from under mouse position. What is the best technique to paint only those 2 lines without going over all polygons and repaint everything at every mouse move.
Thx
This answer is broken.
You want to draw lines and move them without touching the underlying painting.
In the good old days, the method used was to paint with xor composition on top of the drawing, and draw the same pattern (here it would be lines) the same way at the same location to remove it from the screen, again without touching the real painting.
I tried to use this method with the code below to test it out, but it doesn't seem to work. Hopefully, someone with a better knowledge of canvas and js will come forth and fix things up.
function onmousemove(e){
// firt run
var tcanvas = document.getElementById("testCanvas");
var tcontext = tcanvas.getContext("2d");
var pos = {x : e.clientX, y : e.clientY,
w : tcanvas.width, h : tcanvas.height };
var comp = tcontext.globalCompositeOperation;
var paintline = function (p){
tcontext.save();
tcontext.lineWidth = 1;
tcontext.globalCompositeOperation = 'xor';
tcontext.fillStyle = "#000000";
tcontext.moveTo(0,p.y);
tcontext.lineTo(p.w,p.y);
tcontext.moveTo(p.x,0);
tcontext.lineTo(p.x,p.h);
tcontext.stroke();
tcontext.restore();
};
tcontext.save();
paintline(pos);
tcontext.restore();
var next = function(e){
var comp = tcontext.globalCompositeOperation;
paintline(pos);
pos = {x : e.clientX, y : e.clientY,
w : tcanvas.width, h : tcanvas.height };
paintline(pos);
};
document.onmousemove = next;
}
(function draw_stuff(){
// setup canvas
var tcanvas = document.getElementById("testCanvas");
var tcontext = tcanvas.getContext("2d");
// draw square
tcontext.fillStyle = "#FF3366";
tcontext.fillRect(15,15,70,70);
// set composite property
tcontext.globalCompositeOperation = 'xor';
// draw text
tcontext.fillStyle="#0099FF";
tcontext.font = "35px sans-serif";
tcontext.fillText("test", 22, 25);
// draw circle
tcontext.fillStyle = "#0099FF";
tcontext.beginPath();
tcontext.arc(75,75,35,0,Math.PI*2,true);
tcontext.fill();
document.onmousemove = onmousemove;
})();
Also, there are problem with compositing depending on the browser.

raphaelJS 2.1 animate along path

I want to animate a path (actually a set of paths, but I'll get to that) along a curved path.
RaphaelJS 2 removed the animateAlong method, for reasons I haven't been able to discern. Digging into the Raphael documentation's gears demo as abstracted by Zevan, I have got this far:
//adding a custom attribute to Raphael
(function() {
Raphael.fn.addGuides = function() {
this.ca.guide = function(g) {
return {
guide: g
};
};
this.ca.along = function(percent) {
var g = this.attr("guide");
var len = g.getTotalLength();
var point = g.getPointAtLength(percent * len);
var t = {
transform: "t" + [point.x, point.y]
};
return t;
};
};
})();
var paper = Raphael("container", 600, 600);
paper.addGuides();
// the paths
var circ1 = paper.circle(50, 150, 40);
var circ2 = paper.circle(150, 150, 40);
var circ3 = paper.circle(250, 150, 40);
var circ4 = paper.circle(350, 150, 40);
var arc1 = paper.path("M179,204c22.667-7,37,5,38,9").attr({'stroke-width': '2', 'stroke': 'red'});
// the animation
// works but not at the right place
circ3.attr({guide : arc1, along : 1})
.animate({along : 0}, 2000, "linear");
http://jsfiddle.net/hKGLG/4/
I want the third circle to animate along the red path. It is animating now, but at a distance from the red path equal to the third circle's original coordinates. The weird thing is that this happens whether the transform translate in the along object is relative (lowercase "t") or absolute (uppercase "T"). It also always animates in the same spot, even if I nudge it with a transform translation just before the animate call.
Any help very appreciated. I just got off the boat here in vector-land. Pointers are helpful--a working fiddle is even better.
You're just a hop, skip, and jump away from the functionality that you want. The confusion here concerns the interaction between transformations and object properties -- specifically, that transformations do not modify the original object properties. Translating simply adds to, rather than replaces, the original coordinates of your circles.
The solution is extremely straightforward. In your along method:
this.ca.along = function(percent) {
var box = this.getBBox( false ); // determine the fundamental location of the object before transformation occurs
var g = this.attr("guide");
var len = g.getTotalLength();
var point = g.getPointAtLength(percent * len);
var t = {
transform: "...T" + [point.x - ( box.x + ( box.width / 2 ) ), point.y - ( box.y + ( box.height / 2 ) )] // subtract the center coordinates of the object from the translation offset at this point in the guide.
};
return t;
Obviously, there's some room for optimization here (i.e., it might make sense to create all your circles at 0,0 and then translate them to the display coordinates you want, avoiding a lot of iterative math). But it's functional... see here.
One other caveat: the ...T translation won't effect any other transforms that have already been applied to a given circle. This implementation is not guaranteed to play nicely with other transforms.

Categories

Resources