how to translate a dynamically added SVG animation on jointjs when a paper is scaled - svg

I am not able to figure out how to re position an svg animation that i add dynamically on my paper during a zoom in or zoom out.
I add the animation when the link is active according to business logic in the following way.
c = joint.V('circle', { r: 8, fill: 'green' });
c.animateAlongPath({ dur: '4s', repeatCount: 'indefinite' }, canvasPaper.findViewByModel(link).$('.connection')[0]);
joint.V(canvasPaper.svg).append(c)
Now i go to the canvas and zoom in or zoom out the elements in the canvas scale appropriately . i use the paper.scale command. But the animation that i added does not move. I was able to get it scaled down to size but not its position. How do i achieve this?.
My zoom in and zoom out code is as below. I also know that i have to use the translate command on the svg object but i do not know how to calculate the translate values based on the zoomLevel
$('#zoom-in').on('click', function(e) {
e.preventDefault();
zoomLevel = Number((Math.min(1, zoomLevel + 0.2)).toFixed(1));
canvasPaper.scale(zoomLevel, zoomLevel,0,0);
_.each(canvasGraph.getLinks(), function(link) {
if(link.attr('linkActiveAnimationSvgId/text')) {document.getElementById(link.attr('linkActiveAnimationSvgId/text')).setAttribute("transform", "scale(" + zoomLevel + "," + zoomLevel + ")")
}
})
})
My zoom out code is as below
$('#zoom-out').on('click', function(e) {
e.preventDefault();
zoomLevel =Number((Math.max(0.2, zoomLevel - 0.2)).toFixed(1));
canvasPaper.scale(zoomLevel, zoomLevel,0,0);
_.each(canvasGraph.getLinks(), function(link) {
if(link.attr('linkActiveAnimationSvgId/text')) {document.getElementById(link.attr('linkActiveAnimationSvgId/text')).setAttribute("transform", "scale(" + zoomLevel + "," + zoomLevel + ")")
}
})
})

ok all i had to do was to find the view of the paper and then
paperView.vel.append(c)
instead of
joint.V(canvasPaper.svg).append(c)
and now i scale the paper and the animation scales/translates appropriately

Related

How to repeat Paths in Free Drawing?

Please look at
https://stackblitz.com/edit/js-wxidql
Here is my code.
import { fabric } from "fabric";
const canvas = new fabric.Canvas("c", { isDrawingMode: true });
canvas.setBackgroundColor("rgb(255,73,64)", canvas.renderAll.bind(canvas));
canvas.on("path:created", e => {
let mousePath = e.path;
let offsetPath = new fabric.Path();
let offsetLeft = mousePath.left + 60;
let offsetTop = mousePath.top + 60;
offsetPath.setOptions({
path: mousePath.path,
left: offsetLeft,
top: offsetTop,
width: mousePath.width,
height: mousePath.height,
fill: '',
stroke: 'black'
});
canvas.add(offsetPath);
canvas.requestRenderAll();
});
Here is an resulting image of my drawing session.
I drew the happy face in the top left corner of the canvas with my mouse.
The offset image was added by my code.
How can I change my code to make the offset drawing look like the one drawn with my mouse?
Edit: from https://github.com/fabricjs/fabric.js/wiki/When-to-call-setCoords
I tried using
offsetDraw.setCoords();
but I was unable to find a way to make it work.
Edit: What I have presented here is a minimized example. I am working on an larger project where I save each path drawn by the user. Later I recreate those paths in an animation like sequence.
Edit: I made some changes to my code in a effort to understand fabricjs.
const canvas = new fabric.Canvas("c", { isDrawingMode: true });
canvas.setBackgroundColor("rgb(255,73,64)", canvas.renderAll.bind(canvas));
canvas.on("path:created", e => {
let mousePath = e.path;
let offsetPath = new fabric.Path();
let offsetLeft = mousePath.left + 60;
let offsetTop = mousePath.top + 60;
offsetPath.setOptions({
path: mousePath.path,
//left: offsetLeft,
//top: offsetTop,
width: mousePath.width,
height: mousePath.height,
fill: '',
stroke: 'black'
});
canvas.add(offsetPath);
canvas.requestRenderAll();
console.log("mousePath left " + mousePath.left + " top " + mousePath.top);
console.log("offsetPath left " + offsetPath.left + " top " + offsetPath.top);
});
In that code, I commented out the setting of the left and top properties of the offsetPath and added console.log lines. I drew a circle in the top left corner of the canvas with my mouse. The resulting image was the following.
The following was printed in the console.
mousePath left 7.488148148148148 top 10.5
offsetPath left -0.5 top -0.5
I don't understand the results. Why was the offset circle rendered in that position?
Edit: I drew another test with my mouse.
It seems that the code repeats the paths of concentric circles rather well. But, the vertical lines are moved out of their correct position. Their displacements increase as the distance from the center increases. Why?
I found a solution for my own question. But, if someone has a better one, then please post it. Look at
https://stackblitz.com/edit/js-ncxvpg
The following is the code.
const canvas = new fabric.Canvas("c", { isDrawingMode: true });
canvas.setBackgroundColor("rgb(255,73,64)", canvas.renderAll.bind(canvas));
canvas.on("path:created", e => {
let mousePath = e.path;
mousePath.clone(clone => {
clone.setOptions({
left: mousePath.left + 100,
top: mousePath.top + 100
});
canvas.add(clone);
});
});
If someone has an explaination as to why my original code didn't work, then please post it.
thanks for sharing your comments on my question. I am facing a similar issue, just that if I click anywhere on the Canvas the first time. Then the offset issue vanishes. This happens for any object that I programmatically insert into the canvas.
In my case, I suspect that the canvas.pointer is having some offset of the current mouse position. However, when I click and add one very small path of 1pixel, then the pointer offset gets corrected. After this, all subsequent paths or objects created programatically are shown at the correct positions.

[D3][SVG] zoom to object

could you please help me with zooming to SVG objects. no idea how to do this.
i need to zoom and center by click on object, i've made a test plunkr, so please take a look: http://plnkr.co/edit/ZQxhQ8VVoIXjMvdFIvQF
here's full code:
$(function(){
svg = d3.select("#svg");
svg_group = d3.select('#outer_group');
zoom = d3.behavior.zoom()
.translate([0, 0])
.scale(1)
.scaleExtent([.5, 20])
.on("zoom", zoomed);
svg.call(zoom);
function zoomed() {
svg_group.style("stroke-width", 1.5 / d3.event.scale + "px");
svg_group.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
$zoomService.$broadcast('zoom', {
scale: d3.event.scale
});
}
$('.sector').click(function(){
//zoom to somehow??
});
});
You have to use call zoom.event explicitly on the correct element after setting the desired translation and scaling.
var zoomed = false;
$('.sector').click(function(){
var bbox = this.getBBox();
var scale = 4;
// Manually calculating the position to which to transition to
// Will differ on a case by case basis.
svg
.call(zoom
.translate([ (- bbox.x - bbox.width / 2) * scale
, (- bbox.y - bbox.height / 2) * scale
])
.scale(scale).event
);
});
Demo: http://plnkr.co/edit/h1UP87dfQneRCFye9Xtu?p=preview
In the demo, I changed the position of the polygons and the viewBox on the svg to make it easier to calculate the exact coordinates to transition to for the zoom to stay centered. I also added some transitions and zoom-to-zero behavior not shown in the code excerpt above.
Sidenote: You don't have to use jQuery here to bind to click events; D3's selection.on can provide that function.

SVG D3.js append element to SVG g:circle on text mouseover

Scratching my head on this one.
We have a list of text on the left side of the page. Each item in the list has a data-id attribute that makes it easy to match up corresponding schools in our SVG map. This SVG map is a map of the US, and has school locations fed in from a CSV excel sheet and stored in "schools" for access.
circles.selectAll("circles")
.data(schools)
.enter().append("svg:a")
.attr("xlink:href", function(d) { return d.url; })
.append("svg:circle")
.attr("school", function(d, i) { return d.name; })
.attr("id", function(d, i) { return d.id; })
.attr("cx", function(d,i) { return d.longitude; })
.attr("cy", function(d,i) { return d.latitude; })
.attr("r", function(d,i) { return 6; })
.attr("i", function(d,i) { return i; })
.attr("class", "icon")
So when a user hovers over this list of text I previously mentioned, I use this function:
mapSearch = function(id) {
d3.selectAll("circle")
.filter(function(d) {
if (d.id == id) {
return show_bubble_2(d);
}
})
}
Which calls:
show_bubble_2 = function(school_data) {
var school_info = school_data,
latitude = school_info.latitude,
longitude = school_info.longitude;
bubble.css({
"left": (longitude - 75)+"px",
"top": (latitude - 67)+"px"
});
bubble.html("<h1>" + school_info.name + "</h1>" + "<p>" + school_info.city + ", " + school_info.state + "</p>")
.attr("class", function(d) { return school_info.letter; });
bubble.addClass("active");
}
This works unless we start resizing the map to fit different screen sizes, or unless we do special zoom functions on the map. Then the bubbles closer to the west coast are where they're supposed to be but the ones on the east coast are way off. In short, it's a complete nightmare and not at all scalable.
My question: How do I just append this DIV to the corresponding circle ID instead of using an absolute positioned DIV so that no matter what size the map is, the bubble will always pop up right on top of that circle.
I have tried appending inside the if (d.id == id) { } but it always returns errors and so far I haven't figured it out. I'll keep trying something along those lines because I feel like that's the way to do it. If you have a better solution or could point me in the right direction, I would really appreciate it.
Thanks, and have a good one!
You can find the position of the circle even if there is a transform applied by using Element.getBoundingClientRect.
You could use your filtered selection, get the .node() and find its bounding rect. Then by adjusting for the scroll position, you can find the values of top and left to give to your bubble.
This means that the position of the bubble is based on the actual position at which the circle appears on the page, rather than being based on its data, which would require you to take the transforms into account. Try something like this:
mapSearch = function(id) {
// get the selection for the single element that matches id
var c = d3.selectAll("circle")
.filter(function(d) {
if (d.id == id) {
return show_bubble_2(d);
}
});
// get the bounding rect for that selection's node (the actual circle element)
var bcr = c.node().getBoundingClientRect();
// calculate the top/left based on bcr and scroll position
var bubbleTop = bcr.top + document.body.scrollTop + 'px',
bubbleLeft = bcr.left + document.body.scrollLeft + 'px';
// set the top and left positions
bubble.css({
'top': bubbleTop,
'left': bubbleLeft
});
}
Of course, if you are zooming or panning and want the bubble to remain on the circle, you will need to recalculate these values inside your zoom and pan functions, but the process would be the same.
HERE is a demo using circles that are randomly placed within a g element that has a translation and scale applied. Click on an item in the list to place the bubble on the corresponding circle.
A <div> is HTML. A <circle> is SVG. You can't (easily) put HTML elements inside SVG. You'd have to use <foreignobject> elements to do that. (See this question for details.) Alternatively, you could use native SVG elements such as <tspan> instead of <div>

D3 and leaflet returning different SVG in Chrome/Safari and Firefox

I am follow this example to make a map with leaflet and d3, using the latest versions of d3 and leaflet. Something in my code is causing d3 to return different values for the SVG elements in Chrome and FF 28. This is causing the points to be skewed in FF, which has different d values in the PATH elements as well as different transform properties in the SVG elements.
Here is the SVG for Chrome:
<svg width="1049711" height="1802" transform="translate(127,1079)" style="margin-left: -127px; margin-top: -1079px;">
<g class="leaflet-zoom-hide" transform="translate(127,1079)">
<path class="nora f" id="1383_ST_BERNARD_AVE" lat="29.970905251" long="90.064206456" d="M287,210m0,2a2,2 0 1,1 0,-4a2,2 0 1,1 0,4z"></path>
<path class="fixed f" id="7400_ADVENTURE_AVE" lat="30.0599104550001" long="89.9260116889999" d="M1092,-389m0,2a2,2 0 1,1 0,-4a2,2 0 1,1 0,4z"></path>
Here is the SVG for Firefox
<svg width="1049711" height="1802" style="margin-left: -97px; margin-top: -1079px;" transform="translate(97,1079)">
<g class="leaflet-zoom-hide" transform="translate(97,1079)">
<path class="nora f" id="1383_ST_BERNARD_AVE" lat="29.970905251" long="90.064206456" d="M317,210m0,2a2,2 0 1,1 0,-4a2,2 0 1,1 0,4z"/>
<path class="fixed f" id="7400_ADVENTURE_AVE" lat="30.0599104550001" long="89.9260116889999" d="M1122,-389m0,2a2,2 0 1,1 0,-4a2,2 0 1,1 0,4z"/><path class="nora f" id="4170_OLD_GENTILLY_RD" lat="30.0024662600001" long="90.0401487569999" d="M457,-3m0,2a2,2 0 1,1 0,-4a2,2 0 1,1 0,4z"/>
Here is the code that loads the map and projects the points. At the very end there is a function project that returns a different x-value for the point in Chrome and FF 28. I think that this line is creating the overall problem with the code. The x-value is off by different values at different times, so it is hard to write a correction.
var map = new L.Map("map", {center: [29.95, -90.05], zoom: 13, minZoom:10, maxZoom:18})
.addLayer(new L.tileLayer('http://{s}.www.toolserver.org/tiles/bw-mapnik/{z}/{x}/{y}.png'));
var svg = d3.select(map.getPanes().overlayPane).append("svg"),
g = svg.append("g").attr("class", "leaflet-zoom-hide");
//these brackets are jinja2 template syntax. They eventually return 'static/out.json'
d3.json('out.json') }}', function(collection) {
var bounds = d3.geo.bounds(collection),
path = d3.geo.path().projection(project).pointRadius(function (d) {return 2});
console.warn(path)
var feature = g.selectAll("path")
.data(collection.features)
.enter().append("path").attr("class", function(d){
return d.properties.category + " " + d.properties.investigates;;
}).attr("id", function(d){
return d.geometry.address;
}).attr("lat", function(d){
return Math.abs(d.geometry.coordinates[1]);
}).attr("long", function(d){
return Math.abs(d.geometry.coordinates[0]);
});
$(".t").on("click", function(e) {
var adr = "/" + this.id;
showDialog(adr);
});
map.on("viewreset", reset);
reset();
// Reposition the SVG to cover the features.
function reset() {
console.warn(bounds)
var bottomLeft = project(bounds[0]),
topRight = project(bounds[1]);
svg .attr("width", topRight[0] - bottomLeft[0])
.attr("height", bottomLeft[1] - topRight[1])
.style("margin-left", bottomLeft[0] + "px")
.style("margin-top", topRight[1] + "px").attr("transform", "translate(" + -bottomLeft[0] + "," + -topRight[1] + ")");
g .attr("transform", "translate(" + -bottomLeft[0] + "," + -topRight[1] + ")");
feature.attr("d", path)
}
// Use Leaflet to implement a D3 geographic projection.
function project(x) {
var point = map.latLngToLayerPoint(new L.LatLng(x[1], x[0]));
return [point.x, point.y];
}
});
I proposed this as a bug to leaflet. If you try the fiddle in FF 28 and Chrome you will see that line 51 returns different x-values for the same lat/long in Chrome (right x value) and firefox (wrong x value)
I have tried this fiddle in FF 27 and FF 28 -- each of these versions of firefox returns a different (and incorrect) x-value for the point on line 51.
Have I hit a bug in leaflet or d3 or is there an issue with my code? Is there a workaround? What's going on here?
I ended up getting this to work by following this example: https://gist.github.com/ZJONSSON/2957559
Here is the working code:
var path = d3.geo.path().projection(function project(x) {
var point = map.latLngToLayerPoint(new L.LatLng(x[1], x[0]));
return [point.x, point.y];
}).pointRadius(function(d) {
return 2;
});
/* Load and project/redraw on zoom */
d3.json("static/out.json", function(collection) {
var feature = g.selectAll("path")
.data(collection.features)
.enter().append("path")
.attr("class", function(d) {
return d.properties.category + " " + d.properties.investigates + " " + d.properties.thumbnail;
}).attr("id", function(d) {
return d.properties.address;
}).attr("lat", function(d) {
return Math.abs(d.geometry.coordinates[1]);
}).attr("long", function(d) {
return Math.abs(d.geometry.coordinates[0]);
})
.attr("d", path);
map.on("viewreset", function reset() {
feature.attr("d", path);
});
loadThumbs();
});
The problem is how you're calling d3.json.
d3.json('{{url_for('static', filename='out.json') }}', //...
isn't valid. The d3.json function expects its first parameter to be a URL string, not an object. In both FF and webkit you're probably getting random garbage and that's what your code uses to calculate the bounds.
Are you trying to use a template (i.e. mustache) to construct the URL? If so, you're forgetting to render the template.

Display Size/Width Adjustment

I was wandering if there is a way to adjust width of the math mathjax renders. Some math expression I have are longer and won't fit in a box I have created. Is there a way to squeeze it and make it fit maybe by changing the size or width? I have tried using line breaks but that isn't what I want. An example would be a mathjax like this:
2x+3+4 - /intcos(x) dx
234567897+sin(2x)+34567890987654.
Displaying the last line would be a problem because it won't fit in the box. It overflows
Well, you could use \small or \scriptsize or \Tiny (non-standard) or \tiny within the mathematics to make it appear in a smaller size.
Alternatively, you could put a <span style="font-size:70%">...</span> around the mathematics to get the math to be scaled to whatever size you need. E.g.,
<span style="font-size:70%">\(234567897+sin(2x)+34567890987654\)</span>
Note that the math delimiters must be inside the <span>.
I found a solution that doesn't require adding elements or css code:
// resize all LaTeX Display elements to they fit in on screen
function cvonk_ResizeMathJax() {
jQuery('.MathJax_Display').each(function(ii, obj) {
var latex = obj.children[0];
var w = latex.offsetWidth;
var h = latex.offsetHeight;
var W = obj.offsetWidth;
if (w > W) {
obj.style.fontSize = 95 * W / w + "%";
}
});
}
window.MathJax = {
AuthorInit: function() {
MathJax.Hub.Register.StartupHook("Begin", function() {
MathJax.Hub.Queue(function() {
cvonk_ResizeMathJax();
});
});
},
jax: ["input/TeX", "output/HTML-CSS", "output/NativeMML"],
extensions: ["tex2jax.js"]
};
window.addEventListener("resize", function() {
cvonk_ResizeMathJax();
});
From the Google Groups discussion linked to above:
function changeSize(button) {
var myeqn = document.getElementById('myeqn');
myeqn.style.fontSize = button.textContent;
MathJax.Hub.Queue(
['Rerender', MathJax.Hub, 'myeqn'],
function () {
document.getElementById('mylabel').innerHTML =
'width: ' + myeqn.offsetWidth + ", height: " + myeqn.offsetHeight;
});
}
See http://jsfiddle.net/nLyraL1f/ or http://jsfiddle.net/s2bjepk6/.
This is also nice because it gets the width and height of the rendered latex, useful for things like rendering it as an element positioned over a canvas since you can draw things on the canvas around it.

Resources