EzDevInfo.com

svg.js

A lightweight library for manipulating and animating SVG svg.js - A lightweight JavaScript library for manipulating and animating svg svg.js is a lightweight javascript library for manipulating and animating svg using an uncluttered syntax.

svg.js / svg-pan-zoom - doubleclick interactions

I am using Ariutta's svg-pan-zoom with svg.js. I have disabled the native Arriuta doubleclick functionality and have tried adding my own, which ultimately consists of a pan adjustment and an animation.

Usually this works fine, but sometimes when I load my page the doubleclick function acts strangely. According to my debugging, it looks like sometimes when my app loads, the doubleclick function I wrote is called twice for each doubleclick. This causes the animation to behave strangely, and there seems to be no consistent basis for when this issue arises. Restarting my server sometimes works, and sometimes doesn't. I pretty much just have to continue reloading my page until the issue goes away.

My initial thoughts are that maybe there is something off in the load order of my files, and sometimes things load out of order. Currently investigating this. My other thought was that maybe this has something to do with the svg.js animation library or my trying to replace the native double-click function in arriuta's plugin. Thoughts?

myApp.service('AnimatorService', function(){
   this.dblClickBehavior = function(svgCanvas, zoom){   
        $('.node').dblclick(function(){

            // get pan
            pan = zoom.getPan();

            // get screen width and height
            var sizes = zoom.getSizes();
            var centerX = (sizes.width)/2;
            var centerY = (sizes.height)/2;

            // get center position of svg object double clicked 
            var x0 = this.instance.first().attr('cx');
            var y0 = this.instance.first().attr('cy');

            //determine the correct pan value necessary to center the svg
            panAdjustX = centerX - x0*sizes.realZoom;
            panAdjustY = centerY - y0*sizes.realZoom;

            //center the svg object by adjust pan
            zoom.pan({'x' :centerX - x0*sizes.realZoom, 'y' : centerY - y0*sizes.realZoom});

            //simple animation on the object
            this.instance.first().animate().radius(centerX);

        }); 
       }
});

When it behaves correctly, the svg image centers and then grows. When it behaves incorrectly, it centers and then shrinks into nothingness.


Source: (StackOverflow)

svg.js creates double SVGs

I'm trying to use SVG.js to create an SVG, but it seems to create multiple SVG elements in my document instead of just one. I've copy-pasted the code from the SVG.js homepage (http://www.svgjs.com/) into an HTML document, but it does the same thing. Can anybody help me?

<meta http-equiv="content-type" content="text/html; charset=UTF8">
<html>
  <head>
    <title>Drawing</title>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="svg.min.js"></script>
  </head>

  <body>
    <div id="drawing">
    </div>

    <script>
        var draw = SVG('drawing')

        // create image
        var image = draw.image('images/shade.jpg')
        image.size(600, 600).y(-150)

        // create text
        var text = draw.text('SVG.JS').move(300, 0)
        text.font({
          family: 'Source Sans Pro'
        , size: 180
        , anchor: 'middle'
        , leading: 1
        })

        // clip image with text
        image.clipWith(text)

    </script>
  </body>
</html>

Source: (StackOverflow)

Advertisements

Loop animation with svg.js

I have a very simple animation with svg.js that I would like to run on a loop as long as the page is open. I haven't been able to find any thing while looking through either the github, documentation, or stack overflow pages. A working version of the animation without looping can be found here. The important js is:

//create the svg element and the array of circles
var draw = SVG('canvas').size(300, 50);
var circ = [];

for (var i = 0; i < 5; i++) {
    //draw the circles
    circ[i] = draw.circle(12.5).attr({
        fill: '#fff'
    }).cx(i * 37.5 + 12.5).cy(20);

    //first fade the circles out, then fade them back in with a callback
    circ[i].animate(1000, '<>', 1000 + 100 * i).attr({
        opacity: 0
    }).after(function () {
        this.animate(1000, '<>', 250).attr({
            opacity: 1
        });
    });
}

I know this would be pretty easy to do without a js library, but I'm looking at this as just a first step into using svg.js. Later I plan on using it for much more robust animations. Thanks for any advice or pointers.


Source: (StackOverflow)

Creating an SVG Document in SVG.js issue?

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!


Source: (StackOverflow)

Check if the variable is a SVG.js element instance

I'm using the svg.js library.

How can we check if a variable x is an instance of SVG class?


I tried:

new SVG(document.createDocumentFragment()) instanceof SVG     // false
new SVG(document.createDocumentFragment()).contructor === SVG // false

Source: (StackOverflow)

How to use css selector on SVGjs

I try multiple javascript libraries to work with svg

now i play with svgjs.com

but i don't know how to use css selector like snapsvg

var result1 = Snap.select('#id_select');
var result2 = Snap.select('.class_selector');

what is the solution for svgjs ?

i can select childrens but i need make a loop to compare properties for every child :(

what is the shortcut fot get some element inner svg document?

thanks for your attention


Source: (StackOverflow)

SVG performance optimization for browser

I am working on a design tool using SVG. Any other vector formats will be converted to SVG and rendered on the browser with svg.js

I started seeing delays while dragging and moving the elements, when the number of elements increased.

Are there any ways in which I can improve the SVG performance on the browser?

Also, I want give user the ability to rotate and scale elements, render clip arts and add text. Will this make the performance worse?

example

You can see that the drag is pretty slow on that element


Source: (StackOverflow)

How to get id from svgjs object

I tried using jquery's attr function to extract the id from an object generated as such:

var draw = SVG (parent).size (100,100)

but

draw.attr ('id') 

doesn't work. How do I get the id from draw?


Source: (StackOverflow)

How make custom drag event in svg.js

I'm new to programming. I'm making something like vector editor with svg.js I've read documentation and didn't understand how to make custom events at all. Can you guys show an example of drag event?

Actually i'm trying to achieve elements to be removed on drag. For example i want to make tooltip following mouse cursor, that outputs current mouse coordinates. But it gets duplicated every onmousemove event.


Source: (StackOverflow)

Reusing SVG.js code for various SVG's

I'm getting to grips with SVG.js

I have a pattern effect that I've created and would like to use in a number of SVG's.

I can create it in one SVG with the following code...

$( document ).ready(function() {

    var draw = SVG('geo').size(1200, 1700);

    // 100 lines of js creating geometric pattern, effectively this...
    var rect = draw.polygon(coordinates).fill('#fff').stroke({ width: 1, color:'#fff'}).opacity(0)

});

This creates an SVG with ID geo. But I'd like to use this code again to generate various SVG's, ideally with different options (colour etc).

SVG('geo') refers to a particular SVG, how do I make it so I can apply this to any SVG I want on the page?

Hope that made sense


Source: (StackOverflow)

How to store additional data in SVG?

I have a small editor that creates .svg files with diagrams (using svg.js).

The editor stores data about how the file created in its own simple text format, not unlike this one.

I would like to embed the source text directly in the SVG file, so I can load it back without losing any metainformation user specified (like comments and formatting).

What is the proper way to do that? The editor I linked above stores its data in the <source> tag right under <svg>. Is this a good and standards-compliant approach?

<svg 
  xmlns="http://www.w3.org/2000/svg" 
  width="445" height="319" 
  xmlns:xlink="http://www.w3.org/1999/xlink"
>
  <source><![CDATA[Andrew->China: Says Hello
  Note right of China: China thinks\nabout it
  China-->Andrew: How are you?
  Andrew->>China: I am good thanks!]]></source>
  <!-- SVG content here -->
</svg>

Source: (StackOverflow)

Manually rendering SVG glyphs

I am currently implementing a simple SVG text renderer. I am puling path information out of an SVG file for the characters I need to draw.

This is all the appropriate information for font/characters stored in a JSON object:

     window.font = {
        horizAdvX: 487,
        unitsPerEm: 2048,
        ascent: 1638,
        descent: -410,
        glyphs: {
            H: {
                horizAdvX: 1382,
                path: 'M147 14q64 133 244 604q-68 29 -90 80q19 14 135 37l27 66q85 217 115 327.5t81 391.5q81 -14 153 -73t126 -147q-8 -11 -17.5 -26t-22 -38.5t-23 -43.5t-27 -55.5t-27 -58.5l-31.5 -69t-32 -71t-35.5 -80.5t-36.5 -81.5q282 39 488 51q77 223 157.5 399.5t136.5 235.5 q42 -3 124.5 -47.5t101.5 -79.5q-69 -65 -143 -210.5t-140 -336.5q41 -38 41 -92q0 -39 -16 -71q-28 4 -76 8q-69 -219 -111.5 -425t-42.5 -319q0 -33 4 -53q-41 2 -65 15t-31 28.5t-18 32t-27 22.5q-26 9 -44.5 74.5t-18.5 110.5q0 160 104 510q-75 -5 -255 -24.5 t-253 -20.5q-166 -392 -231 -750q-73 18 -126 62.5t-98 117.5z'
            },
            u: {
                horizAdvX: 1011,
                path: 'M174 119q0 98 16 174q43 181 146 386.5t221 291.5q44 0 99 -16t83 -48q-18 -19 -51 -68t-93 -161t-116 -244q-24 -55 -55 -162.5t-31 -156.5q0 -22 15 -37q29 11 73.5 62.5t134.5 174.5q6 9 36 49t47 64t42.5 63t44 75.5t31.5 70.5q19 51 33 84.5t49.5 91.5t77.5 98 q53 0 114 -20.5t80 -44.5q-28 -68 -104.5 -220.5t-115 -259.5t-38.5 -204q0 -51 11.5 -92t22.5 -64.5t11 -32.5q0 -3 -2 -5t-4 -2l-2 -1q-28 0 -88 24t-106 56q-35 29 -50.5 76t-15.5 90q0 44 10 74q-10 1 -52.5 -51t-95.5 -123t-67 -88q-57 -61 -88 -64q-70 3 -138.5 47.5 t-84.5 112.5z'
            },
            // rest of chars ...

Using the excellent svg.js library, I have managed to get this far in the rendering process:

  1. Draw character using path information & SVG.path method
  2. Apply a fixed height to character
  3. Get bounding box for character path
  4. Transform coordinate system so y points down (coordinate system in SVG font is 'upside down')
  5. Draw next character using width of previous character(s) as offset
  6. Repeat

This does draw text. You can see this working on this jsfiddle:

http://jsfiddle.net/dormisher/KVs7E/2/

The thing is everything is the same height, and the exact same distance apart. I need to know how to use the attributes horiz-adv-x, unites-per-em etc, found in the SVG font file, to get the correct horizontal and vertical positioning.

At first it seems simple, horiz-adv-x is simply a scaling value used on the font size, so use that on the horizontal offset and hey presto! But no, doing that ends up with something looking like this:

http://jsfiddle.net/dormisher/KVs7E/3/

What I need to figure out is how the combination of the horizAdvX, and the rest of the simillar values, are used to work out horizontal advance & vertical positioning. I have read through the W3C spec but it makes little sense to me in terms of this stuff.

Be great if anyone could help me out!


Source: (StackOverflow)

Javascript: Difference Between DOM elements and Objects/"Undefined Is Not A Function"

After several hours of trying to figure this out and reading documentation, I'll surrender on this one. I come from a C/C++ background trying to learn Javascript and I'm getting a little confused on what the difference is between a DOM element and an Object. I thought I understood but when I call certain functions on Objects, like ".addEventListener()" I get the famous "Undefined is not a function" error, amongst other funny things. So here's two attempts at the same thing using SVG.js. I'm basically just trying to add an event listener to every shape that I've generated inside of my SVG canvas thus far, such that when any shape is clicked it will change color independent of all others.

One gives me "Undefined..." on the add event listener line, which I solved with the second version but now I'm getting the "Undefined..." error on the only declaration inside of my function.

Could you clarify what the difference is between a DOM element and an Object and then help me understand why the "Undefined is not a function" error is popping up in my second example? Thanks.

Version 1: canvas.get() returns an object, one of the shapes I've generated, error appears on .addEventListener() call

function changeColor(e) {
    this.fill({color: currentColor});
}
//add event listeners for every element of SVG
var it;
for (it=3; it<=18; it++){
    var canvasName = canvas.get(it);
    canvasName.addEventListener("click", changeColor);
}

Version 2: the event listener is now being added to a DOM element and the "Undefined is not a function" error appears in declaration inside of function (line 2)

function changeColor(e) {
    this.fill({color: currentColor});
}
//add event listeners for every element of SVG
var it;
for (it=3; it<=18; it++){
    //get string to search for id in DOM
    var idName = "SvgjsRect" + (1006+it);
    var box = document.getElementById(idName);
    box.addEventListener("click", changeColor);
}

My final version. I realized that they basically abandon all native DOM functions for their own, so I used their event binding methods.

var changeColor = function() {
        this.fill({color: currentColor});
    }
    //add event listeners for every element of SVG
    var it;
    for (it=3; it<=18; it++){
        var box = canvas.get(it);
        box.on('click', changeColor);
    }

Source: (StackOverflow)

SVG JS - text color

Hei,I'm trying to change the text color of a text that I'm adding using svg js. my code looks like this:

var elecChangeText=elecChange.toString();
var elecPercentageText = energyArrow.text(elecChangeText);

elecPercentageText.font({
    family:   'Helvetica', 
    size:     30, 
    color: "#ffffff", 
})
elecPercentageText.cx(energyArrow.cx());
elecPercentageText.cy(energyArrow.cy());

but the text appears in black anyways. any ideas what I'm doing wrong? I've tried to use text-color instead of just color, but that throws an error...


Source: (StackOverflow)

Wrap existing SVG elements using the svg.js library

How can I wrap existing <svg> element in svg.js?

For example:

<svg>
    <circle r="10" cx="10" cy="10" fill="red"></circle>
</svg>

I know this can be built with svg.js very easy, but I take it as example for my question.

var existingSvg = Svg.<some-method>(document.querySelector("svg"));
existingSvg.children(); // circle

How can I do this?

I tried using SVG('<id-ofsvg-element>'), but children() returns an empty array.


Source: (StackOverflow)