Creating an SVG Document in SVG.js issue? - svg

I am new to SVG.js and javascript in general, and I was going over the documentation here http://documentup.com/wout/svg.js#usage/svg-document and was having some issues.
Usage
Create a SVG document
Use the SVG() function to create a SVG document within a given html element:
var draw = SVG('drawing').size(300, 300)
var rect = draw.rect(100, 100).attr({ fill: '#f06' })
so I was assuming from this they want us to call a function so what I've gathered from messing around a little in Three.js is that I need to do
<script>
function SVG()
{
//Use the SVG() function to create a SVG document within a given html
var draw = SVG('drawing').size(300, 300)
var rect = draw.rect(100, 100).attr({ fill: '#f06' })
}
</script>
within the body tag. This doesn't work however. When calling SVG(); I get an error
Uncaught RangeError: Maximum call stack size exceeded (15:22:47:898 | error, javascript)
at SVG (:18:13)
at SVG (:20:12)
at SVG (:20:12)
at SVG (:20:12)
at SVG (:20:12)
at SVG (:20:12)
There are other ways I can do it as mentioned, but it seems that the easiest method would be to call a function, but again I'm not sure if I'm doing this correctly.
I have a background in Java, just getting off of a project with JMonkeyEngine, so I'm not new to programming, but confused with what exactly I need to do with this, since the documentation is extremely vague and seems to suggest that you need to understand their terminology as to where to put the code.
I have also found a few other librarieslike snap.svg, d3, and raphael
http://d3js.org/
raphaeljs.com/
snapsvg.io/
I'm really just trying to create a bunch of pictures/colored boxes (interchangable so essentially a box with an image that can then be turned off and be displayed as a color) with borders, that can respond to mouse even of clicking and dragging around on desktop and mobile browsers. Essentially not much, but it seems like these all have similar features just a different coding feel.
Any advice?
Thank you everyone!

As said by Nils, there is a Hello World example here: https://stackoverflow.com/tags/svg.js/info
You also find plenty of documentation and examples to see what you have to do.
//Use the SVG() function to create a SVG document within a given html
var canvas = SVG(idOfElement)
// now an svg was created in the element with the id
// draw a rectangle
canvas.rect(100,100)

Related

Save canvas as file? (and open file again) (without loosing quality)

The program I'm using is this
var canvas = this.__canvas = new fabric.Canvas('c');
canvas.setHeight(300);
canvas.setWidth(500);
function AddCircle() {
canvas.add(new fabric.Circle({
left: 230/canvas.getZoom(),
top: 140/canvas.getZoom(),
radius: 75/canvas.getZoom(),
fill: 'green',
}));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<button onclick="AddCircle()">Add Circles</button>
<br>
<br>
<button onclick="Saveas()">Save as</button>
<button onclick="Openfile()">Open file</button>
<div class="box">
<canvas id="c"></canvas>
So now. I want to save the canvas (all the content/all the circles or objects) as a file. At this point I have seen that there are a few ways to save, for example, as png. But The problem is that I don't want to loose quality of the work inside of canvas.
I have seen libraries like jason. But I really don't know to implement them.
Also I have seen that working with svg for saving as files is easier since it can be saved/open as .xhml file without loosing quality.
My other question is:
Is there a easy way to convert the canvas to xhml, so when you click save button, you save the file as xhml, once saved back to use it by clicking "open file button" to open the .xhml file and conver it to canvas again (to show the content in the workspace)?
This are just my thinkings, any suggestions, libraries you recommend more or demo snippets for solving this would be very appreciated.
My last is. What do you recommend more, working with canvas libraries or svg libraries?. Im planning to make a very basic app like Prezi.com is (create objects) Online saving files and so... (also I plan to insert svg and maybe animations to the work space)
As you see, now I'm using canvas libraries ( in particular fabric.js). But since I'm starting it'd be easier for me to change if I'm not using the best alternative.
I am not sure that is possible,
HTML Canvas it's a Bitmap, that you draw in with Javascript.
SVG embedded in an HTML document, It's just like a subtree of the DOM, that still has a valid XML representation that any (not sure if any but most), SVG editors and viewers will understand.
You can "emulate" a canvas with SVG, easily by setting a svg or div + svg and then appending all the childs to this svg and because the geometric ideas of drawing in canvas and doing vector graphics are not that different, you could "migrate" to it.
The tip here is to define a viewbox on the SVG as you would define the canvas dimensions, and then, you can preserve your units. (just be careful with the numbers)
Plus it would be easier to attach events to the SVG elements.
To be honest the w3schools tutorial on SVG it's comprehensive enough, the rest from that it's just a good use case and use their building blocks (with javascript)
This is how you would create an SVG element for the DOM.
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttributeNS(null, 'x', 5);
circle.setAttributeNS(null, 'y', 15);
# more code...
I think saving the image as a png file should be just fine. Png compression is lossless and supports transparent images, so drawing a previously saved png file to the canvas should perfectly restore the content without any changes.
Also, I'm not sure if storing it as a svg file would work that well, since svg is a vector graphics format and the canvas is a bitmap. I know it is possible to embed bitmap images in an svg file, but that requires it to be stored in a bitmap format in the first place.

SVG Path Bounding Box in ExtendScript

I am truly stumped at this point. I need to get the bounding box of a path string. I cannot use RaphaelJS because it's integrated too deeply with the browser, and naturally the Illustrator Type Library doesn't include anything to help me.
Where can I go from here? Should I just spend the time implementing my own algorithm?
check out:
http://www.jongware.com/idjshelp.html
or:
http://yearbookmachine.github.io/esdocs/#/Illustrator/PageItem
Rect geometricBounds Read only Property
The bounds of the artwork excluding stroke width.
There is not a lot of info on the Object Model Viewer about it. If it behaves like in InDesign the coordiantes depend on:
The page origin
The used unit
The page size
I hope that helps. You need to have a document open and have some PageItem selected. Should work with mostly everything you can put on a page in Illustrator.
var main = function(){
if(app.activeDocument.selection.length > 0){
var path = app.activeDocument.selection[0];
alert(path.geometricBounds);
}
}
}
main();

SVG Pie chart animation

I have a pie chart svg image, which I get it from server. And my job is to apply animation to this pie chart on client side using snap svg.
Now, the problem is I am new to SVG and I don't know where to start, but I have succeed in animating other chart types.
Can anybody help me with some referral links to solve this problem. I got this link which implements this. But they have not explained how they have achieved this.
Any other kind of animation which can be achieved by snap svg for pie chart can also help me.
edit I have added fiddle of pie chart that I want to animate. I have tried this code:
Snap("svg").select("#pie2d").
animate({ transform: 'r360,150,150' }, 1000, mina.linear );
which does not animate each section of pie chart but complete chart as a whole instead.
This line does not get executed in fiddle as it needs Snap.js
Any help is appreciated.
Thanks in advance.
Snap animations are generally straightforward. Here is a relatively simple example that will introduce some of the elements you may need..load in a file, and animate it once loaded with hover (you must wait until load finish with file imports).
I couldn't put it on a jsfiddle as it needs a remote file, but have it on a test page here with the code below. Also the Snap website getting started page shows loading in svg and animating.
var s = Snap(600,600);
var g = s.group();
var tux = Snap.load("Dreaming_tux.svg", function ( loadedFragment ) {
g.append( loadedFragment );
g.hover( hoverover, hoverout );
} );
var hoverover = function() { g.animate({ transform: 's2r45,150,150' }, 1000, mina.bounce ) };
var hoverout = function() { g.animate({ transform: 's1r0,150,150' }, 1000, mina.bounce ) };
For transforms, they use the Raphael format (same author), which is loosely the following...
t=relative transform, T=absolute transform, s=relative scale, S=absolute Scale
r=relative rotate, R=relative rotate
r
elative means it takes into account previous transforms to accumulate
here it doesn't make much difference, until we combine later
For the specific pie chart, it depends if you already have that in the svg you are pulling from the server, so you may not need to know too much about pie chart creation. If you do, there are some other libraries which support pie charts already (by Raphael, d3.js etc)
I assume you will need to attach a hover element to each segment of the pie chart (you can use something like g.select("segment1")), and scale it up/out, like above.

Scale an SVG (in Dart) using viewBox doesn't work

I recently started working with Google Dart (www.dartlang.org) and playing with SVG.
I am trying to scale a generated SVG to fit into a <div> using a viewBox.
People on StackOverflow already gave me a lot of help.
I am now able to scale paths like this: Dart create and transform an SVG path
But is seems that viewBox is made for scale-to-fit and using it would save me from scaling all paths in the svg separately. That is why I want to use a viewBox.
I tried the following:
// get bounding box of the created svg
Rect bb = path.getBBox();
// create a viewBox for the svg to fit in the div
var viewBox = svg.viewBox.baseVal
..x = bb.x
..y = bb.y
..width = bb.width
..height = bb.height;
// center the image inside the div
svg.preserveAspectRatio.baseVal
..meetOrSlice = PreserveAspectRatio.SVG_MEETORSLICE_MEET
..align = PreserveAspectRatio.SVG_PRESERVEASPECTRATIO_XMIDYMID;
But no scaling happens.
How would I solve this?
While writing this question and retrying to make sure I tried anything before asking here, I found the following solution.
It seems like Dartium (Chrome with a native Dart VM) has a bug (issue 12224) where changes to the viewBox are not reflected directly.
Adding the following code after changes to the viewBox forces Dartium to somehow resize to the requested size:
// add an empty ```<g>``` element to force svg resize
SvgElement g = new SvgElement.tag('g');
svg.append(g);

wkhtmltopdf failure when embed an SVG

Has anyone in this vast space has ever had the luck to successfully create a PDF with an embedded SVG on an HTML? I've been receiving segmentation fault all the time.
Or perhaps is there any other way to embed an SVG into an HTML file and then export it to PDF instead of wkhtmltopdf?
I had similar problem. Seems like javascript embedded in SVG image can cause segmentation fault.
I was generating SVG graphs using pygal Python module. To successfully generate PDF from HTML with SVG graphs I had to do several things:
Remove reference to javascript. (In case of pygal add js=() key to a graph constructor).
Specify image size in svg tag, like
<svg ... width="300" height="200">
(In case of pygal use explicit_size keywoard)
Embed SVG image into img tag in base64 encoded form, like
<img src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0...">
I was using 11th version of wkhtmltopdf.
If this fix doesn't work for others, here's what worked for me with chartist.js, and wkhtmltopdf 0.12.2.1 under Ubuntu 64. (Credit to Panokev)
Add this to your javascript before all other JS.
{
Function.prototype.bind = Function.prototype.bind || function (thisp) {
var fn = this;
return function () {
return fn.apply(thisp, arguments);
};
};
Definitively set width style for chart div, for example - style="width:950px;"
Right .. I managed to pull it off finally ... all needed was a bit of treatment on the original eps file. I opened the file with illustrator and chose to "flatten transparency" .. maybe what it does was to flatten the many layers of the file or something .. then save as svg .. and it rendered nicely in the PDF ..
Hopefully this helps if anyone out there would have the same issue as I did. Thank you! :D
We fixed this problem by adding a width and height attribute to the svg besides the viewbox attribute.

Resources