2

I've created quite a specialised JavaScript application with my own vector graphics. I'd like to host my own hotlinkable API to complement this application, and thought it would be really tidy if I could embed the vector graphics straight into the API.

I know it can be done with fonts (remember cufon, pretty good before google turbo-charged their webfonts), and I don't need to support legacy versions of browsers, so what are your thoughts? How would you go about doing this?

Starkers
  • 10,273
  • 21
  • 95
  • 158
  • I think SVG is XML (so plain text, not binary). I don't know if that helps but maybe it does... – GolezTrol Aug 01 '13 at 15:01
  • I think you need to be more specific about the technical question you are trying to answer. –  Aug 01 '13 at 15:21

2 Answers2

2

Yes, you can embed SVG into your HTML with the, now standard, <svg> tag.

Not only that, but you can also manipulate svg from javascript. I use jquery.svg library. It's easy, and fun, to use.

Try this...

<script type="text/javascript" src="jquery.svg.js"></script>
....

$(function() {
  var div=$("#sample");
  div.svg();
  var svg = div.svg('get');
  svg.load('chart.svg');
  setInterval(function () {
    draw(svg,div.width());
  }, 1000);
});

function draw(svg,w) {
  svg.circle(Math.random()*w, 
             Math.random()*w, 
             Math.random()*(w*.10)+10); 
}
PA.
  • 28,486
  • 9
  • 71
  • 95
  • Looks like we're onto something here, but can I embed the svg into the javascript, not the HTML? That answer would sort of work, but I'd have to recreate all my graphics using jquery.svg's syntax! (I think, I haven't really researched jquery.svg.js. Please correct me!). To embed an Adobe Illustrator svg into html would result in a huge block of code. I want to keep the HTML light as possible and have the API do all the heavy lifting. – Starkers Aug 01 '13 at 16:24
  • yes, you can load complete svg files with this library, `svg.load(svgfile)` – PA. Aug 01 '13 at 17:15
  • Before I dive in, you're saying my API can look something like this: // App V1.0 Copywrite 2013 me ** Jquery minifed code ** // A vector graphic here: Or near enough? Conceptually, this is what I can do? – Starkers Aug 01 '13 at 18:35
  • Sorry, new lines aren't supported in comments, but do you see what I mean? – Starkers Aug 01 '13 at 18:37
  • sorry, i don't quite understand. you want to load in your code the svg code embedded in another tag? – PA. Aug 01 '13 at 18:40
1

Apparently you can embed svg images directly in HTML by adding an svg tag with the right content. So it should be reasonable possible to insert such an element from Javascript or JQuery as well using document.createElement.

[edit] When searching for an example, I found this other question that shows that a little more works needs to be done, because of the namespaces involved.

Community
  • 1
  • 1
GolezTrol
  • 114,394
  • 18
  • 182
  • 210